<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>Threadv</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta property="og:type" content="website">
<meta property="og:title" content="Threadv">
<meta property="og:url" content="http://yoursite.com/page/3/index.html">
<meta property="og:site_name" content="Threadv">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Threadv">
  
    <link rel="alternate" href="/atom.xml" title="Threadv" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">Threadv</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Suche"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main">
  
    <article id="post-rabbitMq" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/03/03/rabbitMq/" class="article-date">
  <time datetime="2019-03-03T03:25:26.000Z" itemprop="datePublished">2019-03-03</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/03/03/rabbitMq/">rabbitMq</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="RabbitMQ-研究"><a href="#RabbitMQ-研究" class="headerlink" title="RabbitMQ 研究"></a>RabbitMQ 研究</h5><ol>
<li>介绍<ol>
<li>RabbitMQ</li>
</ol>
</li>
</ol>
<p>MQ全称为Message Queue，即消息队列， RabbitMQ是由erlang语言开发，基于AMQP（Advanced Message<br>Queue 高级消息队列协议）协议实现的消息队列，它是一种应用程序之间的通信方法，消息队列在分布式系统开<br>发中应用非常广泛。RabbitMQ官方地址：<a href="http://www.rabbitmq.com" target="_blank" rel="noopener">http://www.rabbitmq.com</a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">开发中消息队列通常有如下应用场景：</span><br><span class="line">1、任务异步处理。</span><br><span class="line">将不需要同步处理的并且耗时长的操作由消息队列通知消息接收方进行异步处理。提高了应用程序的响应时间。</span><br><span class="line">2、应用程序解耦合</span><br><span class="line">MQ相当于一个中介，生产方通过MQ与消费方交互，它将应用程序进行解耦合。</span><br><span class="line">市场上还有哪些消息队列？</span><br><span class="line">ActiveMQ，RabbitMQ，ZeroMQ，Kafka，MetaMQ，RocketMQ、Redis。</span><br><span class="line">为什么使用RabbitMQ呢？</span><br><span class="line">1、使得简单，功能强大。</span><br><span class="line">2、基于AMQP协议。</span><br><span class="line">3、社区活跃，文档完善。</span><br><span class="line">4、高并发性能好，这主要得益于Erlang语言。</span><br><span class="line">5、Spring Boot默认已集成RabbitMQ</span><br></pre></td></tr></table></figure>
<p>2.入门</p>
<pre><code>1. 工作原理
</code></pre><p> <img src="https://threadv.github.io/rabbitMQ/yuanli.png" alt="yuanli"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">组成部分说明如下：</span><br><span class="line">Broker：消息队列服务进程，此进程包括两个部分：Exchange和Queue。</span><br><span class="line">Exchange：消息队列交换机，按一定的规则将消息路由转发到某个队列，对消息进行过虑。</span><br><span class="line">Queue：消息队列，存储消息的队列，消息到达队列并转发给指定的消费方。</span><br><span class="line">Producer：消息生产者，即生产方客户端，生产方客户端将消息发送到MQ。</span><br><span class="line">Consumer：消息消费者，即消费方客户端，接收MQ转发的消息。</span><br><span class="line">消息发布接收流程：</span><br><span class="line">-----发送消息-----</span><br><span class="line">1、生产者和Broker建立TCP连接。</span><br><span class="line">2、生产者和Broker建立通道。</span><br><span class="line">3、生产者通过通道消息发送给Broker，由Exchange将消息进行转发。</span><br><span class="line">4、Exchange将消息转发到指定的Queue（队列）</span><br><span class="line">----接收消息-----</span><br><span class="line">1、消费者和Broker建立TCP连接</span><br><span class="line">2、消费者和Broker建立通道</span><br><span class="line">3、消费者监听指定的Queue（队列）</span><br><span class="line">4、当有消息到达Queue时Broker默认将消息推送给消费者。</span><br><span class="line">5、消费者接收到消息。</span><br></pre></td></tr></table></figure>
<p>3.安装</p>
<p>RabbitMQ由Erlang语言开发，Erlang语言用于并发及分布式系统的开发，在电信领域应用广泛，OTP（Open<br>Telecom Platform）作为Erlang语言的一部分，包含了很多基于Erlang开发的中间件及工具库，安装RabbitMQ需<br>要安装Erlang/OTP，并保持版本匹配，</p>
<p>RabbitMQ的下载地址：<a href="http://www.rabbitmq.com/download.html" target="_blank" rel="noopener">http://www.rabbitmq.com/download.html</a></p>
<p>erlang的下载地址： <a href="http://www.erlang.org/downloads" target="_blank" rel="noopener">http://www.erlang.org/downloads</a></p>
<ol>
<li><p>启动</p>
<ol>
<li>从开始菜单启动RabbitMQ<br>在开始菜单找到RabbitMQ的菜单：</li>
</ol>
<p><img src="https://threadv.github.io/rabbitMQ/menu.png" alt="menu"></p>
</li>
</ol>
<ul>
<li>RabbitMQ Service-install :安装服务</li>
<li>RabbitMQ Service-remove 删除服务</li>
<li>RabbitMQ Service-start 启动</li>
<li>RabbitMQ Service-stop 启动</li>
</ul>
<p>安装并运行服务<br>rabbitmq-service.bat install 安装服务 rabbitmq-service.bat stop 停止服务 rabbitmq-service.bat start 启动服务<br>2）安装管理插件<br>安装rabbitMQ的管理插件，方便在浏览器端管理RabbitMQ<br>管理员身份运行 rabbitmq-plugins.bat enable rabbitmq_management<br>北京市昌平区建材城西路金燕龙办公楼一层 电话：400-618-90903、启动成功 登录RabbitMQ<br>进入浏览器，输入：<a href="http://localhost:15672" target="_blank" rel="noopener">http://localhost:15672</a></p>
<p>用 rabbitMQ官方提供的java client测试，目的是对RabbitMQ的交互过程有个清晰的认识。</p>
<p>参考 ：<a href="https://github.com/rabbitmq/rabbitmq-java-client/" target="_blank" rel="noopener">https://github.com/rabbitmq/rabbitmq-java-client/</a></p>
<ul>
<li>创建maven工程</li>
</ul>
<p>创建生产者工程和消费者工程，分别加入RabbitMQ java client的依赖。</p>
<p>test-rabbitmq-producer：生产者工程</p>
<p>test-rabbitmq-consumer：消费者工程</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.rabbitmq<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>amqp‐client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">version</span>&gt;</span>4.0.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span><span class="tag">&lt;<span class="name">!‐‐此版本与spring</span> <span class="attr">boot</span> <span class="attr">1.5.9</span>版本匹配‐‐&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring‐boot‐starter‐logging<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>生产者</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Producer01</span> </span>&#123;</span><br><span class="line">    <span class="comment">//队列名称</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String QUEUE = <span class="string">"helloworld"</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException </span>&#123;</span><br><span class="line">        Connection connection = <span class="keyword">null</span>;</span><br><span class="line">        Channel channel = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">            factory.setHost(<span class="string">"localhost"</span>);</span><br><span class="line">            factory.setPort(<span class="number">5672</span>);</span><br><span class="line">            factory.setUsername(<span class="string">"guest"</span>);</span><br><span class="line">            factory.setPassword(<span class="string">"guest"</span>);</span><br><span class="line">            factory.setVirtualHost(<span class="string">"/"</span>);<span class="comment">//rabbitmq默认虚拟机名称为“/”，虚拟机相当于一个独立的mq服务</span></span><br><span class="line">            器</span><br><span class="line">            <span class="comment">//创建与RabbitMQ服务的TCP连接</span></span><br><span class="line">            connection = factory.newConnection();</span><br><span class="line">            <span class="comment">//创建与Exchange的通道，每个连接可以创建多个通道，每个通道代表一个会话任务</span></span><br><span class="line">            channel = connection.createChannel();</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">            * 声明队列，如果Rabbit中没有此队列将自动创建</span></span><br><span class="line"><span class="comment">            * param1:队列名称</span></span><br><span class="line"><span class="comment">            * param2:是否持久化</span></span><br><span class="line"><span class="comment">            * param3:队列是否独占此连接</span></span><br><span class="line"><span class="comment">            * param4:队列不再使用时是否自动删除此队列</span></span><br><span class="line"><span class="comment">            * param5:队列参数</span></span><br><span class="line"><span class="comment">            */</span></span><br><span class="line">            channel.queueDeclare(QUEUE, <span class="keyword">true</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">            String message = <span class="string">"helloworld小明"</span>+System.currentTimeMillis();</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">            * 消息发布方法</span></span><br><span class="line"><span class="comment">            * param1：Exchange的名称，如果没有指定，则使用Default Exchange</span></span><br><span class="line"><span class="comment">            * param2:routingKey,消息的路由Key，是用于Exchange（交换机）将消息转发到指定的消息队列</span></span><br><span class="line"><span class="comment">            * param3:消息包含的属性</span></span><br><span class="line"><span class="comment">            * param4：消息体</span></span><br><span class="line"><span class="comment">            */</span></span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">            * 这里没有指定交换机，消息将发送给默认交换机，每个队列也会绑定那个默认的交换机，但是不能显</span></span><br><span class="line"><span class="comment">            示绑定或解除绑定</span></span><br><span class="line"><span class="comment">            * 默认的交换机，routingKey等于队列名称</span></span><br><span class="line"><span class="comment">            */</span></span><br><span class="line">            channel.basicPublish(<span class="string">""</span>, QUEUE, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">            System.out.println(<span class="string">"Send Message is:'"</span> + message + <span class="string">"'"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span>(Exception ex)&#123;</span><br><span class="line">            ex.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">if</span>(channel != <span class="keyword">null</span>) &#123;</span><br><span class="line">            channel.close();</span><br><span class="line">        &#125; </span><br><span class="line">        <span class="keyword">if</span>(connection != <span class="keyword">null</span>)&#123;</span><br><span class="line">            connection.close();</span><br><span class="line">        &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>消费者</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Consumer01</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String QUEUE = <span class="string">"helloworld"</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException, TimeoutException </span>&#123;</span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        <span class="comment">//设置MabbitMQ所在服务器的ip和端口</span></span><br><span class="line">        factory.setHost(<span class="string">"127.0.0.1"</span>);</span><br><span class="line">        factory.setPort(<span class="number">5672</span>);</span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">//声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE, <span class="keyword">true</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        <span class="comment">//定义消费方法</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * 消费者接收消息调用此方法</span></span><br><span class="line"><span class="comment">        * <span class="doctag">@param</span> consumerTag 消费者的标签，在channel.basicConsume()去指定</span></span><br><span class="line"><span class="comment">        * <span class="doctag">@param</span> envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志</span></span><br><span class="line"><span class="comment">        (收到消息失败后是否需要重新发送)</span></span><br><span class="line"><span class="comment">        * <span class="doctag">@param</span> properties</span></span><br><span class="line"><span class="comment">        * <span class="doctag">@param</span> body</span></span><br><span class="line"><span class="comment">        * <span class="doctag">@throws</span> IOException</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag,</span></span></span><br><span class="line"><span class="function"><span class="params">            Envelope envelope,</span></span></span><br><span class="line"><span class="function"><span class="params">            AMQP.BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">            <span class="keyword">byte</span>[] body)</span></span></span><br><span class="line"><span class="function">            <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">//交换机</span></span><br><span class="line">                String exchange = envelope.getExchange();</span><br><span class="line">                <span class="comment">//路由key</span></span><br><span class="line">                String routingKey = envelope.getRoutingKey();</span><br><span class="line">                <span class="comment">//消息id</span></span><br><span class="line">                <span class="keyword">long</span> deliveryTag = envelope.getDeliveryTag();</span><br><span class="line">                <span class="comment">//消息内容</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body,<span class="string">"utf‐8"</span>);</span><br><span class="line">                System.out.println(<span class="string">"receive message.."</span> + msg);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">        * 监听队列String queue, boolean autoAck,Consumer callback</span></span><br><span class="line"><span class="comment">        * 参数明细</span></span><br><span class="line"><span class="comment">        * 1、队列名称</span></span><br><span class="line"><span class="comment">        * 2、是否自动回复，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置</span></span><br><span class="line"><span class="comment">        为false则需要手动回复</span></span><br><span class="line"><span class="comment">        * 3、消费消息的方法，消费者接收到消息后调用此方法</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">        channel.basicConsume(QUEUE, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>总结</li>
<li>1、发送端操作流程<ul>
<li>1）创建连接</li>
<li>2）创建通道</li>
<li>3）声明队列</li>
<li>4）发送消息</li>
</ul>
</li>
<li>2、接收端<ul>
<li>1）创建连接</li>
<li>2）创建通道</li>
<li>3）声明队列</li>
<li>4）监听队列</li>
<li>5）接收消息</li>
</ul>
</li>
</ul>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/03/03/rabbitMq/" data-id="ckcc5iwlb0030q4uwf05ejpts" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/消息队列/">消息队列</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-java/Java_基础知识" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/02/18/java/Java_基础知识/" class="article-date">
  <time datetime="2019-02-18T05:18:33.000Z" itemprop="datePublished">2019-02-18</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/02/18/java/Java_基础知识/">Java基础知识</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="Java基础知识"><a href="#Java基础知识" class="headerlink" title="Java基础知识"></a>Java基础知识</h5><p>原文：<a href="https://blog.csdn.net/linzhiqiang0316/article/details/80473906" target="_blank" rel="noopener">https://blog.csdn.net/linzhiqiang0316/article/details/80473906</a></p>
<h5 id="相关概念"><a href="#相关概念" class="headerlink" title="相关概念"></a>相关概念</h5><ol>
<li><p>面向对象的三个特征</p>
<p> 封装，继承，多态，这个应该是人人皆知，有时候也会加上抽象。 </p>
</li>
<li><p>多态的好处</p>
<p> 允许不同类对象对同一消息做出响应，即同一消息可以根据发送对象的不同而采用多种不同的行为方式(发送消息就是函数调用)。主要有以下优点：</p>
<pre><code>可替换性：多态对已存在代码具有可替换性

可扩充性：增加新的子类不影响已经存在的类结构

接口性：多态是超类通过方法签名,向子类提供一个公共接口,由子类来完善或者重写它来实现的。

灵活性

简化性
</code></pre></li>
<li><p>代码中如何实现多态</p>
<p> 实现多态主要有以下三种方式：<br> ​    接口实现<br> ​    继承父类重写方法<br> ​    同一类中进行方法重载</p>
</li>
<li><p>虚拟机是如何实现多态的</p>
<p> 动态绑定技术(dynamic binding)，执行期间判断所引用对象的实际类型，根据实际类型调用对应的方法。</p>
</li>
<li><p>接口的意义</p>
<p> 接口的意义用三个词就可以概括：规范，扩展，回调。</p>
</li>
<li><p>抽象类的意义</p>
<pre><code>抽象类的意义可以用三句话来概括：

为其他子类提供一个公共的类型

封装子类中重复定义的内容

定义抽象方法,子类虽然有不同的实现，但是定义时一致的
</code></pre></li>
<li>接口和抽象类的区别</li>
</ol>
<table>
<thead>
<tr>
<th>比较</th>
<th>抽象类</th>
<th>接口</th>
</tr>
</thead>
<tbody>
<tr>
<td>默认方法</td>
<td>抽象类可以有默认的方法实现</td>
<td>java 8之前,接口中不存在方法的实现</td>
</tr>
<tr>
<td>实现方式</td>
<td>子类使用extends关键字来继承抽象类.如果子类不是抽象类,子类需要提供抽象类中所声明方法的实现</td>
<td>子类使用implements来实现接口,需要提供接口中所有声明的实现</td>
</tr>
<tr>
<td>构造器</td>
<td>抽象类中可以有构造器</td>
<td>接口中不能</td>
</tr>
<tr>
<td>和正常类区别</td>
<td>抽象类不能被实例化</td>
<td>接口则是完全不同的类型</td>
</tr>
<tr>
<td>访问修饰符</td>
<td>抽象方法可以有public,protected和default等修饰</td>
<td>接口默认是public,不能使用其他修饰符</td>
</tr>
<tr>
<td>多继承</td>
<td>一个子类只能存在一个父类</td>
<td>一个子类可以存在多个接口</td>
</tr>
<tr>
<td>添加新方法</td>
<td>想抽象类中添加新方法,可以提供默认的实现,因此可以不修改子类现有的代码</td>
<td>如果往接口中添加新方法,则子类中需要实现该方法</td>
</tr>
</tbody>
</table>
<ol>
<li><p>父类的静态方法能否被子类重写</p>
<p> 不能。重写只适用于实例方法,不能用于静态方法，而子类当中含有和父类相同签名的静态方法，我们一般称之为隐藏</p>
</li>
<li><p>什么是不可变对象</p>
<p> 不可变对象指对象一旦被创建，状态就不能再改变。任何修改都会创建一个新的对象，如 String、Integer及其它包装类</p>
</li>
<li><p>静态变量和实例变量的区别?</p>
<p>静态变量存储在方法区，属于类所有。实例变量存储在堆当中，其引用存在当前线程栈</p>
</li>
<li><p>能否创建一个包含可变对象的不可变对象?</p>
<p>当然可以创建一个包含可变对象的不可变对象的，你只需要谨慎一点，不要共享可变对象的引用就可以了，如果需要变化时，就返回原对象的一个拷贝。最常见的例子就是对象中包含一个日期对象的引用</p>
</li>
<li><p>java 创建对象的几种方式</p>
<p>采用new</p>
<p>通过反射</p>
<p>采用clone</p>
<p>通过序列化机制</p>
<p>前2者都需要显式地调用构造方法。造成耦合性最高的恰好是第一种，因此你发现无论什么框架，只要涉及到解耦必先减少new的使用。</p>
</li>
<li><p>switch中能否使用string做参数</p>
<p>在idk 1.7之前，switch只能支持byte, short, char, int或者其对应的封装类以及Enum类型。从idk 1.7之后switch开始支持String</p>
</li>
<li><p>switch能否作用在byte, long上?</p>
<p>可以用在byte上，但是不能用在long上。</p>
</li>
<li><p>你对String对象的intern()熟悉么?</p>
<p>intern()方法会首先从常量池中查找是否存在该常量值，如果常量池中不存在则现在常量池中创建，如果已经存在则直接返回。</p>
<pre><code>比如 
String s1=”aa”; 
String s2=s1.intern(); 
System.out.print(s1==s2);//返回true
</code></pre></li>
<li><p>String s1=”ab”, String s2=”a”+”b”, String s3=”a”, String s4=”b”, s5=s3+s4请问s5==s2返回什么？</p>
<p> 返回false。在编译过程中，编译器会将s2直接优化为”ab”，会将其放置在常量池当中，s5则是被创建在堆区，相当于s5=new String(“ab”);</p>
</li>
<li><p>Object中有哪些公共方法?</p>
<p>equals()</p>
<p>clone()</p>
<p>getClass()</p>
<p>notify(),notifyAll(),wait()</p>
<p>toString</p>
</li>
<li><p>java当中的四种引用</p>
<p>强引用，软引用，弱引用，虚引用。不同的引用类型主要体现在GC上:<br>​    </p>
<pre><code>强引用：如果一个对象具有强引用，它就不会被垃圾回收器回收。即使当前内存空间不足，JVM也不会回收它，而是抛出 OutOfMemoryError 错误，使程序异常终止。如果想中断强引用和某个对象之间的关联，可以显式地将引用赋值为null，这样一来的话，JVM在合适的时间就会回收该对象。

软引用：在使用软引用时，如果内存的空间足够，软引用就能继续被使用，而不会被垃圾回收器回收，只有在内存不足时，软引用才会被垃圾回收器回收。

弱引用：具有弱引用的对象拥有的生命周期更短暂。因为当 JVM 进行垃圾回收，一旦发现弱引用对象，无论当前内存空间是否充足，都会将弱引用回收。不过由于垃圾回收器是一个优先级较低的线程，所以并不一定能迅速发现弱引用对象。

虚引用：顾名思义，就是形同虚设，如果一个对象仅持有虚引用，那么它相当于没有引用，在任何时候都可能被垃圾回收器回收。
</code></pre></li>
<li><p>WeakReference与SoftReference的区别?</p>
<p>这点在四种引用类型中已经做了解释,这里简单说明一下即可: </p>
<p>虽然 WeakReference 与 SoftReference 都有利于提高 GC 和 内存的效率，但是 WeakReference ，一旦失去最后一个强引用，就会被 GC 回收，而软引用虽然不能阻止被回收，但是可以延迟到 JVM 内存不足的时候</p>
</li>
<li><p>为什么要有不同的引用类型</p>
<p>不像C语言，我们可以控制内存的申请和释放，在Java中有时候我们需要适当的控制对象被回收的时机，因此就诞生了不同的引用类型，可以说不同的引用类型实则是对GC回收时机不可控的妥协。有以下几个使用场景可以充分的说明：</p>
<p>利用软引用和弱引用解决OOM问题：用一个HashMap来保存图片的路径和相应图片对象关联的软引用之间的映射关系，在内存不足时，JVM会自动回收这些缓存图片对象所占用的空间，从而有效地避免了OOM的问题.</p>
<p>通过软引用实现Java对象的高速缓存:比如我们创建了一Person的类，如果每次需要查询一个人的信息,哪怕是几秒中之前刚刚查询过的，都要重新构建一个实例，这将引起大量Person对象的消耗，并且由于这些对象的生命周期相对较短，会引起多次GC影响性能。此时，通过软引用和 HashMap 的结合可以构建高速缓存，提供性能</p>
</li>
<li><p>java中==和eqauls()的区别,equals()和`hashcode的区别</p>
<p>==  是运算符，用于比较两个变量是否相等，而equals是Object类的方法，用于比较两个对象是否相等。默认Object类的equals方法是比较两个对象的地址，此时和  == 的结果一样。换句话说：基本类型比较用==，比较的是他们的值。默认下，对象用==比较时，比较的是内存地址，如果需要比较对象内容，需要重写equal方法</p>
</li>
<li><p>equals()和hashcode()的联系</p>
<p>hashCode()是Object类的一个方法，返回一个哈希值。如果两个对象根据equal()方法比较相等，那么调用这两个对象中任意一个对象的hashCode()方法必须产生相同的哈希值。<br>如果两个对象根据eqaul()方法比较不相等，那么产生的哈希值不一定相等(碰撞的情况下还是会相等的。)</p>
</li>
<li><p>a.hashCode()有什么用?与a.equals(b)有什么关系</p>
<p>hashCode() 方法是相应对象整型的 hash 值。它常用于基于 hash 的集合类，如 Hashtable、HashMap、LinkedHashMap等等。它与 equals() 方法关系特别紧密。根据 Java 规范，使用 equal() 方法来判断两个相等的对象，必须具有相同的 hashcode。</p>
<p>将对象放入到集合中时，首先判断要放入对象的hashcode是否已经在集合中存在，不存在则直接放入集合。如果hashcode相等，然后通过equal()方法判断要放入对象与集合中的任意对象是否相等：如果equal()判断不相等，直接将该元素放入集合中，否则不放入</p>
</li>
<li><p>有没有可能两个不相等的对象有相同的hashcode</p>
<p>有可能，两个不相等的对象可能会有相同的 hashcode 值，这就是为什么在 hashmap 中会有冲突。如果两个对象相等，必须有相同的hashcode 值，反之不成立</p>
</li>
<li><p>可以在hashcode中使用随机数字吗?</p>
<p>不行，因为同一对象的 hashcode 值必须是相同的</p>
</li>
<li><p>a==b与a.equals(b)有什么区别</p>
<p>如果a 和b 都是对象，则 a==b 是比较两个对象的引用，只有当 a 和 b 指向的是堆中的同一个对象才会返回 true，而 a.equals(b) 是进行逻辑比较，所以通常需要重写该方法来提供逻辑一致性的比较。例如，String 类重写 equals() 方法，所以可以用于两个不同对象，但是包含的字母相同的比较</p>
</li>
<li><p>3*0.1==0.3返回值是什么</p>
<p>false，因为有些浮点数不能完全精确的表示出来</p>
</li>
<li><p>a=a+b与a+=b有什么区别吗?</p>
<p>+=操作符会进行隐式自动类型转换，此处a+=b隐式的将加操作的结果类型强制转换为持有结果的类型，而a=a+b则不会自动进行类型转换。如：<br>byte a = 127;<br>byte b = 127;<br>b = a + b; // error : cannot convert from int to byte<br>b += a; // ok<br>（译者注：这个地方应该表述的有误，其实无论 a+b 的值为多少，编译器都会报错，因为 a+b 操作会将 a、b 提升为 int 类型，所以将 int 类型赋值给 byte 就会编译出错）</p>
</li>
<li><p>short s1= 1; s1 = s1 + 1; 该段代码是否有错,有的话怎么改？</p>
<p>有错误，short类型在进行运算时会自动提升为int类型，也就是说s1+1的运算结果是int类型。</p>
</li>
<li><p>short s1= 1; s1 += 1; 该段代码是否有错，有的话怎么改？</p>
<p>+=操作符会自动对右边的表达式结果强转匹配左边的数据类型，所以没错。</p>
</li>
<li><p>&amp; 和 &amp;&amp;的区别</p>
<p>首先记住&amp;是位操作，而&amp;&amp;是逻辑运算符。另外需要记住逻辑运算符具有短路特性，而&amp;不具备短路特性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span></span>&#123;</span><br><span class="line">   <span class="keyword">static</span> String name;</span><br><span class="line"> </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span></span>&#123;</span><br><span class="line">       <span class="keyword">if</span>(name!=<span class="keyword">null</span>&amp;userName.equals(<span class="string">""</span>))&#123;</span><br><span class="line">           System.out.println(<span class="string">"ok"</span>);</span><br><span class="line">       &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">           System.out.println(<span class="string">"erro"</span>);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>一个java文件内部可以有类？(非内部类)</p>
<p>只能有一个public公共类，但是可以有多个default修饰的类。</p>
</li>
<li><p>如何正确的退出多层嵌套循环？</p>
<p>使用标号和break;</p>
<p>通过在外层循环中添加标识符</p>
</li>
<li><p>内部类的作用</p>
<p>内部类可以有多个实例，每个实例都有自己的状态信息，并且与其他外围对象的信息相互独立.在单个外围类当中，可以让多个内部类以不同的方式实现同一接口，或者继承同一个类.创建内部类对象的时刻不依赖于外部类对象的创建。内部类并没有令人疑惑的”is-a”管系，它就像是一个独立的实体。</p>
<p>内部类提供了更好的封装，除了该外围类，其他类都不能访问</p>
</li>
<li><p>final, finalize和finally的不同之处</p>
<p>final 是一个修饰符，可以修饰变量、方法和类。如果 final 修饰变量，意味着该变量的值在初始化后不能被改变。</p>
<p>finalize 方法是在对象被回收之前调用的方法，给对象自己最后一个复活的机会，但是什么时候调用 finalize 没有保证。</p>
<p>finally 是一个关键字，与 try 和 catch 一起用于异常的处理。finally 块一定会被执行，无论在 try 块中是否有发生异常</p>
</li>
<li><p>clone()是哪个类的方法?</p>
<p>java.lang.Cloneable 是一个标示性接口，不包含任何方法，clone 方法在 object 类中定义。并且需要知道 clone() 方法是一个本地方法，这意味着它是由 c 或 c++ 或 其他本地语言实现的</p>
</li>
<li><p>深拷贝和浅拷贝的区别是什么?</p>
<p>浅拷贝：被复制对象的所有变量都含有与原来的对象相同的值，而所有的对其他对象的引用仍然指向原来的对象。换言之，浅拷贝仅仅复制所考虑的对象，而不复制它所引用的对象。</p>
<p>深拷贝：被复制对象的所有变量都含有与原来的对象相同的值，而那些引用其他对象的变量将指向被复制过的新对象，而不再是原有的那些被引用的对象。换言之，深拷贝把要复制的对象所引用的对象都复制了一遍</p>
</li>
<li><p>static都有哪些用法?</p>
<p>几乎所有的人都知道static关键字这两个基本的用法：静态变量和静态方法。也就是被static所修饰的变量/方法都属于类的静态资源，类实例所共享。</p>
<p>除了静态变量和静态方法之外，static也用于静态块，多用于初始化操作：</p>
<pre><code>public calss PreCache{
   static{
       //执行相关操作
   }
}
</code></pre><p>此外static也多用于修饰内部类，此时称之为静态内部类。</p>
<p>最后一种用法就是静态导包，即import static.import static是在JDK 1.5之后引入的新特性，可以用来指定导入某个类中的静态资源，并且不需要使用类名。资源名，可以直接使用资源名，比如：<br>​<br>​    </p>
<pre><code>import static java.lang.Math.*;

public class Test{

   public static void main(String[] args){
       //System.out.println(Math.sin(20));传统做法
       System.out.println(sin(20));
   }
}
</code></pre></li>
<li><p>final有哪些用法</p>
<p>final也是很多面试喜欢问的地方，能回答下以下三点就不错了：<br>​    </p>
<pre><code>1.被final修饰的类不可以被继承 
2.被final修饰的方法不可以被重写 
3.被final修饰的变量不可以被改变。如果修饰引用，那么表示引用不可变，引用指向的内容可变。
4.被final修饰的方法，JVM会尝试将其内联，以提高运行效率 
5.被final修饰的常量，在编译阶段会存入常量池中。

回答出编译器对final域要遵守的两个重排序规则更好：
1.在构造函数内对一个final域的写入，与随后把这个被构造对象的引用赋值给一个引用变量,这两个操作之间不能重排序。
2.初次读一个包含final域的对象的引用，与随后初次读这个final域,这两个操作之间不能重排序。
</code></pre><h5 id="数据类型相关"><a href="#数据类型相关" class="headerlink" title="数据类型相关"></a>数据类型相关</h5></li>
<li><p>java中int char,long各占多少字节?</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>类型</th>
<th>位数</th>
<th>字节数</th>
</tr>
</thead>
<tbody>
<tr>
<td>short</td>
<td>2</td>
<td>16</td>
</tr>
<tr>
<td>int</td>
<td>4</td>
<td>32</td>
</tr>
<tr>
<td>long</td>
<td>8</td>
<td>64</td>
</tr>
<tr>
<td>float</td>
<td>4</td>
<td>32</td>
</tr>
<tr>
<td>double</td>
<td>8</td>
<td>64</td>
</tr>
<tr>
<td>char</td>
<td>2</td>
<td>16</td>
</tr>
</tbody>
</table>
<ol>
<li><p>64位的JVM当中,int的长度是多少?</p>
<p> Java 中，int 类型变量的长度是一个固定值，与平台无关，都是 32 位。意思就是说，在 32 位 和 64 位 的Java 虚拟机中，int 类型的长度是相同的</p>
</li>
<li><p>int和Integer的区别</p>
<p> Integer是int的包装类型，在拆箱和装箱中，二者自动转换。int是基本类型，直接存数值，而integer是对象，用一个引用指向这个对象</p>
</li>
<li><p>int 和Integer谁占用的内存更多?</p>
<p> Integer 对象会占用更多的内存。Integer是一个对象，需要存储对象的元数据。但是 int 是一个原始类型的数据，所以占用的空间更少</p>
</li>
<li><p>String, StringBuffer和StringBuilder区别</p>
<p> String是字符串常量，final修饰：StringBuffer字符串变量(线程安全)；</p>
<p> StringBuilder 字符串变量(线程不安全)。</p>
</li>
<li><p>String和StringBuffer</p>
<p> String和StringBuffer主要区别是性能：String是不可变对象，每次对String类型进行操作都等同于产生了一个新的String对象，然后指向新的String对象。所以尽量不在对String进行大量的拼接操作，否则会产生很多临时对象，导致GC开始工作，影响系统性能。</p>
<p> StringBuffer是对对象本身操作，而不是产生新的对象，因此在有大量拼接的情况下，我们建议使用StringBuffer。</p>
<p> 但是需要注意现在JVM会对String拼接做一定的优化：<br> String s=“This is only ”+”simple”+”test”会被虚拟机直接优化成String s=“This is only simple test”，此时就不存在拼接过程。</p>
</li>
<li><p>StringBuffer和StringBuilder</p>
<p> StringBuffer是线程安全的可变字符串，其内部实现是可变数组。StringBuilder是jdk 1.5新增的，其功能和StringBuffer类似，但是非线程安全。因此，在没有多线程问题的前提下，使用StringBuilder会取得更好的性能</p>
</li>
<li><p>什么是编译器常量？使用它有什么风险？</p>
<p> 公共静态不可变（public static final ）变量也就是我们所说的编译期常量，这里的 public 可选的。实际上这些变量在编译时会被替换掉，因为编译器知道这些变量的值，并且知道这些变量在运行时不能改变。这种方式存在的一个问题是你使用了一个内部的或第三方库中的公有编译时常量，但是这个值后面被其他人改变了，但是你的客户端仍然在使用老的值，甚至你已经部署了一个新的jar。为了避免这种情况，当你在更新依赖 JAR 文件时，确保重新编译你的程序</p>
</li>
<li><p>java当中使用什么类型表示价格比较好?</p>
<p> 如果不是特别关心内存和性能的话，使用BigDecimal，否则使用预定义精度的 double 类型</p>
</li>
<li><p>如何将byte转为String</p>
<p>可以使用 String 接收 byte[] 参数的构造器来进行转换，需要注意的点是要使用的正确的编码，否则会使用平台默认编码，这个编码可能跟原来的编码相同，也可能不同</p>
</li>
<li><p>可以将int强转为byte类型么?会产生什么问题?</p>
<p>我们可以做强制转换，但是Java中int是32位的而byte是8 位的，所以,如果强制转化int类型的高24位将会被丢弃，byte 类型的范围是从-128到128</p>
</li>
</ol>
<h5 id="关于垃圾回收"><a href="#关于垃圾回收" class="headerlink" title="关于垃圾回收"></a>关于垃圾回收</h5><ol>
<li><p>你知道哪些垃圾回收算法?</p>
<p> 垃圾回收从理论上非常容易理解,具体的方法有以下几种: </p>
<ol>
<li>标记-清除 </li>
<li>标记-复制 </li>
<li>标记-整理 </li>
<li><p>分代回收<br>更详细的内容参见深入理解垃圾回收算法：</p>
<p><a href="http://blog.csdn.net/dd864140130/article/details/50084471" target="_blank" rel="noopener">http://blog.csdn.net/dd864140130/article/details/50084471</a></p>
</li>
</ol>
</li>
<li><p>如何判断一个对象是否应该被回收</p>
<p> 这就是所谓的对象存活性判断，常用的方法有两种：1.引用计数法;　2.对象可达性分析。由于引用计数法存在互相引用导致无法进行GC的问题，所以目前JVM虚拟机多使用对象可达性分析算法</p>
</li>
<li><p>简单的解释一下垃圾回收</p>
<p> Java 垃圾回收机制最基本的做法是分代回收。内存中的区域被划分成不同的世代，对象根据其存活的时间被保存在对应世代的区域中。一般的实现是划分成3个世代：年轻、年老和永久。内存的分配是发生在年轻世代中的。当一个对象存活时间足够长的时候，它就会被复制到年老世代中。对于不同的世代可以使用不同的垃圾回收算法。进行世代划分的出发点是对应用中对象存活时间进行研究之后得出的统计规律。一般来说，一个应用中的大部分对象的存活时间都很短。比如局部变量的存活时间就只在方法的执行过程中。基于这一点，对于年轻世代的垃圾回收算法就可以很有针对性</p>
</li>
<li><p>调用System.gc()会发生什么?</p>
<p> 通知GC开始工作，但是GC真正开始的时间不确定</p>
</li>
</ol>
<h5 id="进程-线程相关"><a href="#进程-线程相关" class="headerlink" title="进程,线程相关"></a>进程,线程相关</h5><ol>
<li><p>说说进程，线程，协程之间的区别</p>
<p> 简而言之，进程是程序运行和资源分配的基本单位，一个程序至少有一个进程，一个进程至少有一个线程。进程在执行过程中拥有独立的内存单元，而多个线程共享内存资源，减少切换次数，从而效率更高。线程是进程的一个实体，是cpu调度和分派的基本单位，是比程序更小的能独立运行的基本单位。同一进程中的多个线程之间可以并发执行</p>
</li>
<li><p>你了解守护线程吗？它和非守护线程有什么区别</p>
<p> 程序运行完毕，jvm会等待非守护线程完成后关闭，但是jvm不会等待守护线程。守护线程最典型的例子就是GC线程</p>
</li>
<li><p>什么是多线程上下文切换</p>
<p> 多线程的上下文切换是指CPU控制权由一个已经正在运行的线程切换到另外一个就绪并等待获取CPU执行权的线程的过程</p>
</li>
<li><p>创建两种线程的方式?他们有什么区别?</p>
<p> 通过实现java.lang.Runnable或者通过扩展java.lang.Thread类。相比扩展Thread，实现Runnable接口可能更优.原因有二：</p>
<p> Java不支持多继承。因此扩展Thread类就代表这个子类不能扩展其他类。而实现Runnable接口的类还可能扩展另一个类。</p>
<p> 类可能只要求可执行即可，因此继承整个Thread类的开销过大</p>
</li>
<li><p>Thread类中的start()和run()方法有什么区别?</p>
<p> start()方法被用来启动新创建的线程，而且start()内部调用了run()方法，这和直接调用run()方法的效果不一样。当你调用run()方法的时候，只会是在原来的线程中调用，没有新的线程启动，start()方法才会启动新线程</p>
</li>
<li><p>怎么检测一个线程是否持有对象监视器</p>
<p> Thread类提供了一个holdsLock(Object obj)方法，当且仅当对象obj的监视器被某条线程持有的时候才会返回true，注意这是一个static方法，这意味着”某条线程”指的是当前线程</p>
</li>
<li><p>Runnable和Callable的区别</p>
<p> Runnable接口中的run()方法的返回值是void，它做的事情只是纯粹地去执行run()方法中的代码而已；Callable接口中的call()方法是有返回值的，是一个泛型，和Future、FutureTask配合可以用来获取异步执行的结果。<br>这其实是很有用的一个特性，因为多线程相比单线程更难、更复杂的一个重要原因就是因为多线程充满着未知性，某条线程是否执行了？某条线程执行了多久？某条线程执行的时候我们期望的数据是否已经赋值完毕？无法得知，我们能做的只是等待这条多线程的任务执行完毕而已。而Callable+Future/FutureTask却可以方便获取多线程运行的结果，可以在等待时间太长没获取到需要的数据的情况下取消该线程的任务。</p>
</li>
<li><p>什么导致线程阻塞</p>
<p> 阻塞指的是暂停一个线程的执行以等待某个条件发生（如某资源就绪），学过操作系统的同学对它一定已经很熟悉了。Java 提供了大量方法来支持阻塞，下面让我们逐一分析</p>
</li>
</ol>
<table>
<thead>
<tr>
<th>方法</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>sleep()</td>
<td>sleep() 允许 指定以毫秒为单位的一段时间作为参数，它使得线程在指定的时间内进入阻塞状态，不能得到CPU 时间，指定的时间一过，线程重新进入可执行状态。 典型地，sleep() 被用在等待某个资源就绪的情形：测试发现条件不满足后，让线程阻塞一段时间后重新测试，直到条件满足为止</td>
</tr>
<tr>
<td>suspend() 和 resume()</td>
<td>两个方法配套使用，suspend()使得线程进入阻塞状态，并且不会自动恢复，必须其对应的resume() 被调用，才能使得线程重新进入可执行状态。典型地，suspend() 和 resume() 被用在等待另一个线程产生的结果的情形：测试发现结果还没有产生后，让线程阻塞，另一个线程产生了结果后，调用 resume() 使其恢复</td>
</tr>
<tr>
<td>yield()</td>
<td>yield() 使当前线程放弃当前已经分得的CPU 时间，但不使当前线程阻塞，即线程仍处于可执行状态，随时可能再次分得 CPU 时间。调用 yield() 的效果等价于调度程序认为该线程已执行了足够的时间从而转到另一个线程</td>
</tr>
<tr>
<td>wait() 和 notify()</td>
<td>两个方法配套使用，wait() 使得线程进入阻塞状态，它有两种形式，一种允许 指定以毫秒为单位的一段时间作为参数，另一种没有参数，前者当对应的 notify() 被调用或者超出指定时间时线程重新进入可执行状态，后者则必须对应的 notify() 被调用。</td>
</tr>
</tbody>
</table>
<ol>
<li><p>wait(),notify()和suspend(),resume()之间的区别</p>
<p> 初看起来它们与 suspend() 和 resume() 方法对没有什么分别，但是事实上它们是截然不同的。区别的核心在于，前面叙述的所有方法，阻塞时都不会释放占用的锁（如果占用了的话），而这一对方法则相反。上述的核心区别导致了一系列的细节上的区别。</p>
<p> 首先，前面叙述的所有方法都隶属于 Thread 类，但是这一对却直接隶属于 Object 类，也就是说，所有对象都拥有这一对方法。初看起来这十分不可思议，但是实际上却是很自然的，因为这一对方法阻塞时要释放占用的锁，而锁是任何对象都具有的，调用任意对象的 wait() 方法导致线程阻塞，并且该对象上的锁被释放。而调用 任意对象的notify()方法则导致从调用该对象的 wait() 方法而阻塞的线程中随机选择的一个解除阻塞（但要等到获得锁后才真正可执行）。</p>
<p> 其次，前面叙述的所有方法都可在任何位置调用，但是这一对方法却必须在 synchronized 方法或块中调用，理由也很简单，只有在synchronized 方法或块中当前线程才占有锁，才有锁可以释放。同样的道理，调用这一对方法的对象上的锁必须为当前线程所拥有，这样才有锁可以释放。因此，这一对方法调用必须放置在这样的 synchronized 方法或块中，该方法或块的上锁对象就是调用这一对方法的对象。若不满足这一条件，则程序虽然仍能编译，但在运行时会出现IllegalMonitorStateException 异常。</p>
<p> wait() 和 notify() 方法的上述特性决定了它们经常和synchronized关键字一起使用，将它们和操作系统进程间通信机制作一个比较就会发现它们的相似性：synchronized方法或块提供了类似于操作系统原语的功能，它们的执行不会受到多线程机制的干扰，而这一对方法则相当于 block 和wakeup 原语（这一对方法均声明为 synchronized）。它们的结合使得我们可以实现操作系统上一系列精妙的进程间通信的算法（如信号量算法），并用于解决各种复杂的线程间通信问题。</p>
<p> 关于 wait() 和 notify() 方法最后再说明两点：<br> 第一：调用 notify() 方法导致解除阻塞的线程是从因调用该对象的 wait() 方法而阻塞的线程中随机选取的，我们无法预料哪一个线程将会被选择，所以编程时要特别小心，避免因这种不确定性而产生问题。</p>
<p> 第二：除了 notify()，还有一个方法 notifyAll() 也可起到类似作用，唯一的区别在于，调用 notifyAll() 方法将把因调用该对象的 wait() 方法而阻塞的所有线程一次性全部解除阻塞。当然，只有获得锁的那一个线程才能进入可执行状态。</p>
<p> 谈到阻塞，就不能不谈一谈死锁，略一分析就能发现，suspend() 方法和不指定超时期限的 wait() 方法的调用都可能产生死锁。遗憾的是，Java 并不在语言级别上支持死锁的避免，我们在编程中必须小心地避免死锁。</p>
<p> 以上我们对 Java 中实现线程阻塞的各种方法作了一番分析，我们重点分析了 wait() 和 notify() 方法，因为它们的功能最强大，使用也最灵活，但是这也导致了它们的效率较低，较容易出错。实际使用中我们应该灵活使用各种方法，以便更好地达到我们的目的。</p>
</li>
<li><p>产生死锁的条件</p>
<pre><code>1.互斥条件：一个资源每次只能被一个进程使用。 
2.请求与保持条件：一个进程因请求资源而阻塞时，对已获得的资源保持不放。 
3.不剥夺条件:进程已获得的资源，在末使用完之前，不能强行剥夺。 
4.循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
</code></pre></li>
<li><p>为什么wait()方法和notify()/notifyAll()方法要在同步块中被调用</p>
<p>这是JDK强制的，wait()方法和notify()/notifyAll()方法在调用前都必须先获得对象的锁</p>
</li>
<li><p>wait()方法和notify()/notifyAll()方法在放弃对象监视器时有什么区别</p>
<p>wait()方法和notify()/notifyAll()方法在放弃对象监视器的时候的区别在于：wait()方法立即释放对象监视器，notify()/notifyAll()方法则会等待线程剩余代码执行完毕才会放弃对象监视器。</p>
</li>
<li><p>wait()与sleep()的区别</p>
<p>关于这两者已经在上面进行详细的说明,这里就做个概括好了:</p>
<pre><code>sleep()来自Thread类，和wait()来自Object类。调用sleep()方法的过程中，线程不会释放对象锁。而 调用 wait 方法线程会释放对象锁

sleep()睡眠后不出让系统资源，wait让其他线程可以占用CPU

sleep(milliseconds)需要指定一个睡眠时间，时间一到会自动唤醒.而wait()需要配合notify()或者notifyAll()使用
</code></pre></li>
<li><p>为什么wait, nofity和nofityAll这些方法不放在Thread类当中</p>
<p>一个很明显的原因是JAVA提供的锁是对象级的而不是线程级的，每个对象都有锁，通过线程获得。如果线程需要等待某些锁那么调用对象中的wait()方法就有意义了。如果wait()方法定义在Thread类中，线程正在等待的是哪个锁就不明显了。简单的说，由于wait，notify和notifyAll都是锁级别的操作，所以把他们定义在Object类中因为锁属于对象</p>
</li>
<li><p>怎么唤醒一个阻塞的线程</p>
<p>如果线程是因为调用了wait()、sleep()或者join()方法而导致的阻塞，可以中断线程，并且通过抛出InterruptedException来唤醒它；如果线程遇到了IO阻塞，无能为力，因为IO是操作系统实现的，Java代码并没有办法直接接触到操作系统</p>
</li>
<li><p>什么是多线程的上下文切换</p>
<p>多线程的上下文切换是指CPU控制权由一个已经正在运行的线程切换到另外一个就绪并等待获取CPU执行权的线程的过程</p>
</li>
<li><p>synchronized和ReentrantLock的区别</p>
<p>synchronized是和if、else、for、while一样的关键字，ReentrantLock是类，这是二者的本质区别。既然ReentrantLock是类，那么它就提供了比synchronized更多更灵活的特性，可以被继承、可以有方法、可以有各种各样的类变量，ReentrantLock比synchronized的扩展性体现在几点上：<br>​    </p>
<pre><code>（1）ReentrantLock可以对获取锁的等待时间进行设置，这样就避免了死锁 
（2）ReentrantLock可以获取各种锁的信息 
（3）ReentrantLock可以灵活地实现多路通知 
另外，二者的锁机制其实也是不一样的:ReentrantLock底层调用的是Unsafe的park方法加锁，synchronized操作的应该是对象头中mark word
</code></pre></li>
<li><p>FutureTask是什么</p>
<p>这个其实前面有提到过，FutureTask表示一个异步运算的任务。FutureTask里面可以传入一个Callable的具体实现类，可以对这个异步运算的任务的结果进行等待获取、判断是否已经完成、取消任务等操作。当然，由于FutureTask也是Runnable接口的实现类，所以FutureTask也可以放入线程池中</p>
</li>
<li><p>一个线程如果出现了运行时异常怎么办?</p>
<p>如果这个异常没有被捕获的话，这个线程就停止执行了。另外重要的一点是：如果这个线程持有某个某个对象的监视器，那么这个对象监视器会被立即释放</p>
</li>
<li><p>Java当中有哪几种锁</p>
<p>自旋锁: 自旋锁在JDK1.6之后就默认开启了。基于之前的观察，共享数据的锁定状态只会持续很短的时间，为了这一小段时间而去挂起和恢复线程有点浪费，所以这里就做了一个处理，让后面请求锁的那个线程在稍等一会，但是不放弃处理器的执行时间，看看持有锁的线程能否快速释放。为了让线程等待，所以需要让线程执行一个忙循环也就是自旋操作。在jdk6之后，引入了自适应的自旋锁，也就是等待的时间不再固定了，而是由上一次在同一个锁上的自旋时间及锁的拥有者状态来决定。</p>
<p>偏向锁: 在JDK1.之后引入的一项锁优化，目的是消除数据在无竞争情况下的同步原语。进一步提升程序的运行性能。 偏向锁就是偏心的偏，意思是这个锁会偏向第一个获得他的线程，如果接下来的执行过程中，改锁没有被其他线程获取，则持有偏向锁的线程将永远不需要再进行同步。偏向锁可以提高带有同步但无竞争的程序性能，也就是说他并不一定总是对程序运行有利，如果程序中大多数的锁都是被多个不同的线程访问，那偏向模式就是多余的，在具体问题具体分析的前提下，可以考虑是否使用偏向锁。</p>
<p>轻量级锁: 为了减少获得锁和释放锁所带来的性能消耗，引入了“偏向锁”和“轻量级锁”，所以在Java SE1.6里锁一共有四种状态，无锁状态，偏向锁状态，轻量级锁状态和重量级锁状态，它会随着竞争情况逐渐升级。锁可以升级但不能降级，意味着偏向锁升级成轻量级锁后不能降级成偏向锁。</p>
</li>
<li><p>如何在两个线程间共享数据</p>
<p>通过在线程之间共享对象就可以了，然后通过wait/notify/notifyAll、await/signal/signalAll进行唤起和等待，比方说阻塞队列BlockingQueue就是为线程之间共享数据而设计的。</p>
</li>
<li><p>如何正确的使用wait()？使用if还是while？</p>
<p>wait() 方法应该在循环调用，因为当线程获取到 CPU 开始执行的时候，其他条件可能还没有满足，所以在处理前，循环检测条件是否满足会更好。下面是一段标准的使用 wait 和 notify 方法的代码：</p>
<pre><code>synchronized (obj) {
   while (condition does not hold)
     obj.wait(); // (Releases lock, and reacquires on wakeup)
     ... // Perform action appropriate to condition
}
</code></pre></li>
<li><p>什么是线程局部变量ThreadLocal</p>
<p>线程局部变量是局限于线程内部的变量，属于线程自身所有，不在多个线程间共享。Java提供ThreadLocal类来支持线程局部变量，是一种实现线程安全的方式。但是在管理环境下（如 web 服务器）使用线程局部变量的时候要特别小心，在这种情况下，工作线程的生命周期比任何应用变量的生命周期都要长。任何线程局部变量一旦在工作完成后没有释放，Java 应用就存在内存泄露的风险。</p>
</li>
<li><p>ThreadLoal的作用是什么?</p>
<p>简单说ThreadLocal就是一种以空间换时间的做法在每个Thread里面维护了一个ThreadLocal.ThreadLocalMap把数据进行隔离，数据不共享，自然就没有线程安全方面的问题了。</p>
</li>
<li><p>生产者消费者模型的作用是什么?</p>
<p>（1）通过平衡生产者的生产能力和消费者的消费能力来提升整个系统的运行效率，这是生产者消费者模型最重要的作用。</p>
<p>（2）解耦，这是生产者消费者模型附带的作用，解耦意味着生产者和消费者之间的联系少，联系越少越可以独自发展而不需要收到相互的制约。</p>
</li>
<li><p>写一个生产者-消费者队列</p>
<p>可以通过阻塞队列实现，也可以通过wait-notify来实现。</p>
<p>使用阻塞队列来实现：</p>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line">//消费者</span><br><span class="line">public class Producer implements Runnable&#123;</span><br><span class="line">   private final BlockingQueue&lt;Integer&gt; queue;</span><br><span class="line"> </span><br><span class="line">   public Producer(BlockingQueue q)&#123;</span><br><span class="line">       this.queue=q;</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">   @Override</span><br><span class="line">   public void run() &#123;</span><br><span class="line">       try &#123;</span><br><span class="line">           while (true)&#123;</span><br><span class="line">               Thread.sleep(1000);//模拟耗时</span><br><span class="line">               queue.put(produce());</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;catch (InterruptedException e)&#123;</span><br><span class="line"> </span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">   private int produce() &#123;</span><br><span class="line">       int n=new Random().nextInt(10000);</span><br><span class="line">       System.out.println(&quot;Thread:&quot; + Thread.currentThread().getId() + &quot; produce:&quot; + n);</span><br><span class="line">       return n;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line">//消费者</span><br><span class="line">public class Consumer implements Runnable &#123;</span><br><span class="line">   private final BlockingQueue&lt;Integer&gt; queue;</span><br><span class="line"> </span><br><span class="line">   public Consumer(BlockingQueue q)&#123;</span><br><span class="line">       this.queue=q;</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">   @Override</span><br><span class="line">   public void run() &#123;</span><br><span class="line">       while (true)&#123;</span><br><span class="line">           try &#123;</span><br><span class="line">               Thread.sleep(2000);//模拟耗时</span><br><span class="line">               consume(queue.take());</span><br><span class="line">           &#125;catch (InterruptedException e)&#123;</span><br><span class="line"> </span><br><span class="line">           &#125;</span><br><span class="line"> </span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">   private void consume(Integer n) &#123;</span><br><span class="line">       System.out.println(&quot;Thread:&quot; + Thread.currentThread().getId() + &quot; consume:&quot; + n);</span><br><span class="line"> </span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line">//测试</span><br><span class="line">public class Main &#123;</span><br><span class="line"> </span><br><span class="line">   public static void main(String[] args) &#123;</span><br><span class="line">       BlockingQueue&lt;Integer&gt; queue=new ArrayBlockingQueue&lt;Integer&gt;(100);</span><br><span class="line">       Producer p=new Producer(queue);</span><br><span class="line">       Consumer c1=new Consumer(queue);</span><br><span class="line">       Consumer c2=new Consumer(queue);</span><br><span class="line"> </span><br><span class="line">       new Thread(p).start();</span><br><span class="line">       new Thread(c1).start();</span><br><span class="line">       new Thread(c2).start();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li><p>如果你提交任务时，线程池队列已满，这时会发生什么</p>
<p>如果你使用的LinkedBlockingQueue，也就是无界队列的话，没关系，继续添加任务到阻塞队列中等待执行，因为LinkedBlockingQueue可以近乎认为是一个无穷大的队列，可以无限存放任务；如果你使用的是有界队列比方说ArrayBlockingQueue的话，任务首先会被添加到ArrayBlockingQueue中，ArrayBlockingQueue满了，则会使用拒绝策略RejectedExecutionHandler处理满了的任务，默认是AbortPolicy</p>
</li>
<li><p>为什么要使用线程池.</p>
<p>避免频繁地创建和销毁线程，达到线程对象的重用。另外，使用线程池还可以根据项目灵活地控制并发的数目。</p>
</li>
<li><p>java中用到的线程调度算法是什么</p>
<p>抢占式。一个线程用完CPU之后，操作系统会根据线程优先级、线程饥饿情况等数据算出一个总的优先级并分配下一个时间片给某个线程执行。</p>
</li>
<li><p>Thread.sleep(0)的作用是什么</p>
<p>由于Java采用抢占式的线程调度算法，因此可能会出现某条线程常常获取到CPU控制权的情况，为了让某些优先级比较低的线程也能获取到CPU控制权，可以使用Thread.sleep(0)手动触发一次操作系统分配时间片的操作，这也是平衡CPU控制权的一种操作。</p>
</li>
<li><p>什么是CAS</p>
<p>CAS，全称为Compare and Swap，即比较-替换。假设有三个操作数：内存值V、旧的预期值A、要修改的值B，当且仅当预期值A和内存值V相同时，才会将内存值修改为B并返回true，否则什么都不做并返回false。当然CAS一定要volatile变量配合，这样才能保证每次拿到的变量是主内存中最新的那个值，否则旧的预期值A对某条线程来说，永远是一个不会变的值A，只要某次CAS操作失败，永远都不可能成功。</p>
</li>
<li><p>什么是乐观锁和悲观锁</p>
<p>乐观锁：乐观锁认为竞争不总是会发生，因此它不需要持有锁，将比较-替换这两个动作作为一个原子操作尝试去修改内存中的变量，如果失败则表示发生冲突，那么就应该有相应的重试逻辑。</p>
<p>悲观锁：悲观锁认为竞争总是会发生，因此每次对某资源进行操作时，都会持有一个独占的锁，就像synchronized，不管三七二十一，直接上了锁就操作资源了。</p>
</li>
<li><p>ConcurrentHashMap的并发度是什么?</p>
<p>ConcurrentHashMap的并发度就是segment的大小，默认为16，这意味着最多同时可以有16条线程操作ConcurrentHashMap，这也是ConcurrentHashMap对Hashtable的最大优势，任何情况下，Hashtable能同时有两条线程获取Hashtable中的数据吗？</p>
</li>
<li><p>ConcurrentHashMap的工作原理</p>
<p>ConcurrentHashMap在jdk 1.6和jdk 1.8实现原理是不同的。</p>
<p>jdk 1.6:<br>​<br>ConcurrentHashMap是线程安全的，但是与Hashtablea相比，实现线程安全的方式不同。Hashtable是通过对hash表结构进行锁定，是阻塞式的，当一个线程占有这个锁时，其他线程必须阻塞等待其释放锁。ConcurrentHashMap是采用分离锁的方式，它并没有对整个hash表进行锁定，而是局部锁定，也就是说当一个线程占有这个局部锁时，不影响其他线程对hash表其他地方的访问。 </p>
<p>具体实现:ConcurrentHashMap内部有一个Segment.</p>
<p>jdk 1.8</p>
<p>在jdk 8中，ConcurrentHashMap不再使用Segment分离锁，而是采用一种乐观锁CAS算法来实现同步问题，但其底层还是“数组+链表-&gt;红黑树”的实现</p>
</li>
<li><p>CyclicBarrier和CountDownLatch区别</p>
<p>这两个类非常类似，都在java.util.concurrent下，都可以用来表示代码运行到某个点上，二者的区别在于：</p>
<p>CyclicBarrier的某个线程运行到某个点上之后，该线程即停止运行，直到所有的线程都到达了这个点，所有线程才重新运行；CountDownLatch则不是，某线程运行到某个点上之后，只是给某个数值-1而已，该线程继续运行。</p>
<p>CyclicBarrier只能唤起一个任务，CountDownLatch可以唤起多个任务</p>
<p>CyclicBarrier可重用，CountDownLatch不可重用，计数值为0该CountDownLatch就不可再用了。</p>
</li>
<li><p>java中的++操作符线程安全么?</p>
<p>不是线程安全的操作。它涉及到多个指令，如读取变量值，增加，然后存储回内存，这个过程可能会出现多个线程交差</p>
</li>
<li><p>你有哪些多线程开发良好的实践?</p>
<p>给线程命名</p>
<p>最小化同步范围</p>
<p>优先使用volatile</p>
<p>尽可能使用更高层次的并发工具而非wait和notify()来实现线程通信,如BlockingQueue,Semeaphore</p>
<p>优先使用并发容器而非同步容器.</p>
<p>考虑使用线程池</p>
</li>
</ol>
<h5 id="关于集合"><a href="#关于集合" class="headerlink" title="关于集合"></a>关于集合</h5><ol>
<li><p>Java中的集合及其继承关系</p>
<p> 关于集合的体系是每个人都应该烂熟于心的,尤其是对我们经常使用的List,Map的原理更该如此.这里我们看这张图即可: </p>
<p> 更多内容可见集合类总结：</p>
<p> <a href="http://write.blog.csdn.net/postedit/40826423" target="_blank" rel="noopener">http://write.blog.csdn.net/postedit/40826423</a></p>
</li>
<li><p>poll()方法和remove()方法区别？</p>
<p> poll() 和 remove() 都是从队列中取出一个元素，但是 poll() 在获取元素失败的时候会返回空，但是 remove() 失败的时候会抛出异常。</p>
</li>
<li><p>LinkedHashMap和PriorityQueue的区别</p>
<p> PriorityQueue 是一个优先级队列,保证最高或者最低优先级的的元素总是在队列头部，但是 LinkedHashMap 维持的顺序是元素插入的顺序。当遍历一个 PriorityQueue 时，没有任何顺序保证，但是 LinkedHashMap 课保证遍历顺序是元素插入的顺序</p>
</li>
<li><p>WeakHashMap与HashMap的区别是什么?</p>
<p> WeakHashMap 的工作与正常的 HashMap 类似，但是使用弱引用作为 key，意思就是当 key 对象没有任何引用时，key/value 将会被回收。</p>
</li>
<li><p>ArrayList和LinkedList的区别?</p>
<p> 最明显的区别是 ArrrayList底层的数据结构是数组，支持随机访问，而 LinkedList 的底层数据结构是双向循环链表，不支持随机访问。使用下标访问一个元素，ArrayList 的时间复杂度是 O(1)，而 LinkedList 是 O(n)。</p>
</li>
<li><p>ArrayList和Array有什么区别?</p>
<p> Array可以容纳基本类型和对象，而ArrayList只能容纳对象。</p>
<p> Array是指定大小的，而ArrayList大小是固定的</p>
</li>
<li><p>ArrayList和HashMap默认大小?</p>
<p> 在 Java 7 中，ArrayList 的默认大小是 10 个元素，HashMap 的默认大小是16个元素（必须是2的幂）。这就是 Java 7 中 ArrayList 和 HashMap 类的代码片段。</p>
<pre><code>private static final int DEFAULT_CAPACITY = 10;

//from HashMap.java JDK 7
static final int DEFAULT_INITIAL_CAPACITY = 1 &lt;&lt; 4;
</code></pre></li>
<li><p>Comparator和Comparable的区别?</p>
<p> Comparable 接口用于定义对象的自然顺序，而 comparator 通常用于定义用户定制的顺序。Comparable 总是只有一个，但是可以有多个 comparator 来定义对象的顺序。</p>
</li>
<li><p>如何实现集合排序?</p>
<p> 你可以使用有序集合，如 TreeSet 或 TreeMap，你也可以使用有顺序的的集合，如 list，然后通过 Collections.sort() 来排序。</p>
</li>
<li><p>如何打印数组内容</p>
<p>你可以使用 Arrays.toString() 和 Arrays.deepToString() 方法来打印数组。由于数组没有实现 toString() 方法，所以如果将数组传递给 System.out.println() 方法，将无法打印出数组的内容，但是 Arrays.toString() 可以打印每个元素</p>
</li>
<li><p>LinkedList的是单向链表还是双向?</p>
<p>双向循环列表，具体实现自行查阅源码。</p>
</li>
<li><p>TreeMap是实现原理</p>
<p>采用红黑树实现，具体实现自行查阅源码。</p>
</li>
<li><p>遍历ArrayList时如何正确移除一个元素</p>
<p>该问题的关键在于面试者使用的是 ArrayList 的 remove() 还是 Iterator 的 remove()方法。这有一段示例代码，是使用正确的方式来实现在遍历的过程中移除元素，而不会出现 ConcurrentModificationException 异常的示例代码</p>
</li>
<li><p>什么是ArrayMap?它和HashMap有什么区别?</p>
<p>ArrayMap是Android SDK中提供的，非Android开发者可以略过。</p>
<p>ArrayMap是用两个数组来模拟map，更少的内存占用空间,更高的效率。</p>
<p>具体参考这篇文章：ArrayMap VS HashMap：<a href="http://lvable.com/?p=217%5D" target="_blank" rel="noopener">http://lvable.com/?p=217%5D</a></p>
</li>
<li><p>HashMap的实现原理</p>
<ol>
<li><p>HashMap概述： HashMap是基于哈希表的Map接口的非同步实现。此实现提供所有可选的映射操作，并允许使用null值和null键。此类不保证映射的顺序，特别是它不保证该顺序恒久不变。 </p>
</li>
<li><p>HashMap的数据结构： 在java编程语言中，最基本的结构就是两种，一个是数组，另外一个是模拟指针（引用），所有的数据结构都可以用这两个基本结构来构造的，HashMap也不例外。HashMap实际上是一个“链表散列”的数据结构，即数组和链表的结合体。</p>
</li>
</ol>
<p>当我们往Hashmap中put元素时,首先根据key的hashcode重新计算hash值,根绝hash值得到这个元素在数组中的位置(下标),如果该数组在该位置上已经存放了其他元素,那么在这个位置上的元素将以链表的形式存放,新加入的放在链头,最先加入的放入链尾.如果数组中该位置没有元素,就直接将该元素放到数组的该位置上.</p>
<p>需要注意Jdk 1.8中对HashMap的实现做了优化,当链表中的节点数据超过八个之后,该链表会转为红黑树来提高查询效率,从原来的O(n)到O(logn)</p>
</li>
<li><p>你了解Fail-Fast机制吗？</p>
<p>Fail-Fast即我们常说的快速失败，</p>
<p>更多内容参看fail-fast机制：<a href="http://blog.csdn.net/chenssy/article/details/38151189" target="_blank" rel="noopener">http://blog.csdn.net/chenssy/article/details/38151189</a></p>
</li>
<li><p>Fail-fast和Fail-safe有什么区别</p>
<p>Iterator的fail-fast属性与当前的集合共同起作用，因此它不会受到集合中任何改动的影响。Java.util包中的所有集合类都被设计为fail-&gt;fast的，而java.util.concurrent中的集合类都为fail-safe的。当检测到正在遍历的集合的结构被改变时，Fail-fast迭代器抛出ConcurrentModificationException，而fail-safe迭代器从不抛出ConcurrentModificationException。</p>
</li>
</ol>
<h5 id="关于日期"><a href="#关于日期" class="headerlink" title="关于日期"></a>关于日期</h5><ol>
<li><p>SimpleDateFormat是线程安全的吗?</p>
<p> 非常不幸，DateFormat 的所有实现，包括 SimpleDateFormat 都不是线程安全的，因此你不应该在多线程序中使用，除非是在对外线程安全的环境中使用，如 将 SimpleDateFormat 限制在 ThreadLocal 中。如果你不这么做，在解析或者格式化日期的时候，可能会获取到一个不正确的结果。因此，从日期、时间处理的所有实践来说，我强力推荐 joda-time 库。</p>
</li>
<li><p>如何格式化日期?</p>
<p> Java 中，可以使用 SimpleDateFormat 类或者 joda-time 库来格式日期。DateFormat 类允许你使用多种流行的格式来格式化日期。参见答案中的示例代码，代码中演示了将日期格式化成不同的格式，如 dd-MM-yyyy 或 ddMMyyyy。</p>
</li>
</ol>
<h5 id="关于异常"><a href="#关于异常" class="headerlink" title="关于异常"></a>关于异常</h5><ol>
<li><p>简单描述java异常体系</p>
<p> 相比没有人不了解异常体系,关于异常体系的更多信息可以见</p>
<p> 白话异常机制：<a href="http://blog.csdn.net/dd864140130/article/details/42504189" target="_blank" rel="noopener">http://blog.csdn.net/dd864140130/article/details/42504189</a></p>
</li>
<li><p>throw和throws的区别</p>
<p> throw用于主动抛出java.lang.Throwable 类的一个实例化对象，意思是说你可以通过关键字 throw 抛出一个 Error 或者 一个Exception，如：throw new IllegalArgumentException(“size must be multiple of 2″),<br>而throws 的作用是作为方法声明和签名的一部分，方法被抛出相应的异常以便调用者能处理。Java 中，任何未处理的受检查异常强制在 throws 子句中声明。</p>
</li>
</ol>
<h5 id="关于序列化"><a href="#关于序列化" class="headerlink" title="关于序列化"></a>关于序列化</h5><ol>
<li><p>Java 中，Serializable 与 Externalizable 的区别</p>
<p> Serializable 接口是一个序列化 Java 类的接口，以便于它们可以在网络上传输或者可以将它们的状态保存在磁盘上，是 JVM 内嵌的默认序列化方式，成本高、脆弱而且不安全。Externalizable 允许你控制整个序列化过程，指定特定的二进制格式，增加安全机制。</p>
</li>
</ol>
<h5 id="关于JVM"><a href="#关于JVM" class="headerlink" title="关于JVM"></a>关于JVM</h5><ol>
<li><p>JVM特性</p>
<p> 平台无关性. </p>
<p> Java语言的一个非常重要的特点就是与平台的无关性。而使用Java虚拟机是实现这一特点的关键。一般的高级语言如果要在不同的平台上运行，至少需要编译成不同的目标代码。而引入Java语言虚拟机后，Java语言在不同平台上运行时不需要重新编译。Java语言使用模式Java虚拟机屏蔽了与具体平台相关的信息，使得Java语言编译程序只需生成在Java虚拟机上运行的目标代码（字节码），就可以在多种平台上不加修改地运行。Java虚拟机在执行字节码时，把字节码解释成具体平台上的机器指令执行。</p>
</li>
<li><p>简单解释一下类加载器</p>
<p> 有关类加载器一般会问你四种类加载器的应用场景以及双亲委派模型,</p>
<p> 更多的内容参看深入理解JVM加载器：</p>
<p> <a href="http://blog.csdn.net/dd864140130/article/details/49817357" target="_blank" rel="noopener">http://blog.csdn.net/dd864140130/article/details/49817357</a></p>
</li>
<li><p>简述堆和栈的区别</p>
<p> VM 中堆和栈属于不同的内存区域，使用目的也不同。栈常用于保存方法帧和局部变量，而对象总是在堆上分配。栈通常都比堆小，也不会在多个线程之间共享，而堆被整个 JVM 的所有线程共享。</p>
</li>
<li><p>简述JVM内存分配</p>
<p> 基本数据类型比变量和对象的引用都是在栈分配的。</p>
<p> 堆内存用来存放由new创建的对象和数组。</p>
<p> 类变量（static修饰的变量），程序在一加载的时候就在堆中为类变量分配内存，堆中的内存地址存放在栈中。</p>
<p> 实例变量：当你使用java关键字new的时候，系统在堆中开辟并不一定是连续的空间分配给变量，是根据零散的堆内存地址，通过哈希算法换算为一长串数字以表征这个变量在堆中的”物理位置”,实例变量的生命周期–当实例变量的引用丢失后，将被GC（垃圾回收器）列入可回收“名单”中，但并不是马上就释放堆中内存。</p>
<p> 局部变量: 由声明在某方法，或某代码段里（比如for循环），执行到它的时候在栈中开辟内存，当局部变量一但脱离作用域，内存立即释放。</p>
</li>
</ol>
<h5 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h5><ol>
<li><p>java当中采用的是大端还是小端?<br>XML解析的几种方式和特点</p>
<p> DOM, SAX, PULL三种解析方式：</p>
<p> DOM:消耗内存：先把xml文档都读到内存中，然后再用DOM API来访问树形结构，并获取数据。这个写起来很简单，但是很消耗内存。要是数据过大，手机不够牛逼，可能手机直接死机</p>
<p> SAX:解析效率高，占用内存少，基于事件驱动的：更加简单地说就是对文档进行顺序扫描，当扫描到文档(document)开始与结束、元素(element)开始与结束、文档(document)结束等地方时通知事件处理函数，由事件处理函数做相应动作，然后继续同样的扫描，直至文档结束。</p>
<p> PULL:与 SAX 类似，也是基于事件驱动，我们可以调用它的next（）方法，来获取下一个解析事件（就是开始文档，结束文档，开始标签，结束标签），当处于某个元素时可以调用XmlPullParser的getAttributte()方法来获取属性的值，也可调用它的nextText()获取本节点的值。</p>
</li>
<li><p>JDK 1.7特性</p>
<p> 然 JDK 1.7 不像 JDK 5 和 8 一样的大版本，但是，还是有很多新的特性，如 try-with-resource 语句，这样你在使用流或者资源的时候，就不需要手动关闭，Java 会自动关闭。Fork-Join 池某种程度上实现 Java 版的 Map-reduce。允许 Switch 中有 String 变量和文本。菱形操作符(&lt;&gt;)用于类型推断，不再需要在变量声明的右边申明泛型，因此可以写出可读写更强、更简洁的代码。</p>
</li>
<li><p>JDK 1.8特性</p>
<p> java 8 在 Java 历史上是一个开创新的版本，下面 JDK 8 中 5 个主要的特性： </p>
<p> Lambda 表达式，允许像对象一样传递匿名函数 </p>
<p> Stream API，充分利用现代多核 CPU，可以写出很简洁的代码 </p>
<p> Date 与 Time API，最终，有一个稳定、简单的日期和时间库可供你使用 </p>
<p> 扩展方法，现在，接口中可以有静态、默认方法。 </p>
<p> 重复注解，现在你可以将相同的注解在同一类型上使用多次。</p>
</li>
<li><p>Maven和ANT有什么区别?</p>
<p> 虽然两者都是构建工具，都用于创建 Java 应用，但是 Maven 做的事情更多，在基于“约定优于配置”的概念下，提供标准的Java 项目结构，同时能为应用自动管理依赖（应用中所依赖的 JAR 文件。</p>
</li>
<li><p>JDBC最佳实践</p>
<p> 优先使用批量操作来插入和更新数据</p>
<p> 使用PreparedStatement来避免SQL漏洞</p>
<p> 使用数据连接池</p>
<p> 通过列名来获取结果集</p>
</li>
<li><p>IO操作最佳实践</p>
<p> 使用有缓冲的IO类,不要单独读取字节或字符</p>
<p> 使用NIO和NIO 2或者AIO,而非BIO</p>
<p> 在finally中关闭流</p>
<p> 使用内存映射文件获取更快的IO</p>
</li>
</ol>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/02/18/java/Java_基础知识/" data-id="ckcc5iwo2006dq4uwdwwerkmk" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/java/">java</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-消息队列简单使用" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/02/16/消息队列简单使用/" class="article-date">
  <time datetime="2019-02-16T11:20:26.000Z" itemprop="datePublished">2019-02-16</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/02/16/消息队列简单使用/">MnsUtil</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="消息队列简单使用"><a href="#消息队列简单使用" class="headerlink" title="消息队列简单使用"></a>消息队列简单使用</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br></pre></td><td class="code"><pre><span class="line">package com.ifenghui.queue;</span><br><span class="line"></span><br><span class="line">import com.aliyun.mns.client.CloudAccount;</span><br><span class="line">import com.aliyun.mns.client.CloudQueue;</span><br><span class="line">import com.aliyun.mns.client.MNSClient;</span><br><span class="line">import com.aliyun.mns.model.Message;</span><br><span class="line">import com.aliyun.mns.model.QueueMeta;</span><br><span class="line">import com.fasterxml.jackson.core.JsonProcessingException;</span><br><span class="line">import com.fasterxml.jackson.databind.ObjectMapper;</span><br><span class="line">import com.ifenghui.app.comment.exception.FhException;</span><br><span class="line">import org.apache.log4j.Logger;</span><br><span class="line">import org.springframework.beans.factory.annotation.Value;</span><br><span class="line">import org.springframework.integration.support.json.Jackson2JsonObjectMapper;</span><br><span class="line">import org.springframework.stereotype.Component;</span><br><span class="line">import java.lang.reflect.Method;</span><br><span class="line">import java.util.Date;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">@Component</span><br><span class="line">public class MnsUtil&#123;</span><br><span class="line"></span><br><span class="line">    Logger logger= Logger.getLogger(MnsUtil.class);</span><br><span class="line">    public MNSClient getClient() &#123;</span><br><span class="line">        return client;</span><br><span class="line">    &#125;</span><br><span class="line">    private static MNSClient client = null;</span><br><span class="line">    @Value(&quot;$&#123;mns.accountendpoint&#125;&quot;)</span><br><span class="line">    String endPoint;//=&quot;http://20900454.mns.cn-hangzhou.aliyuncs.com&quot;;</span><br><span class="line">    @Value(&quot;$&#123;mns.accesskeyid&#125;&quot;)</span><br><span class="line">    String accessKeyId;//=&quot;xxxxxxxxx&quot;;</span><br><span class="line">    @Value(&quot;$&#123;mns.accesskeysecret&#125;&quot;)</span><br><span class="line">    String accessKeySecret;//=&quot;xxxxxxxxxxxx&quot;;</span><br><span class="line">    @Value(&quot;$&#123;mns.prefix&#125;&quot;)</span><br><span class="line">    String mnsPrefix;</span><br><span class="line">    public MnsUtil() &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public MnsUtil(String endPoint,String accessKeyId,String accessKeySecret,String mnsPrefix) &#123;</span><br><span class="line">        this.endPoint=endPoint;</span><br><span class="line">        this.accessKeySecret=accessKeySecret;</span><br><span class="line">        this.accessKeyId=accessKeyId;</span><br><span class="line">        this.mnsPrefix=mnsPrefix;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void init()&#123;</span><br><span class="line">        if(client!=null)&#123;</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line">        CloudAccount account = new CloudAccount(</span><br><span class="line">                accessKeyId,</span><br><span class="line">                accessKeySecret,</span><br><span class="line">                endPoint);</span><br><span class="line">        client = account.getMNSClient();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public CloudQueue createQueue(String queueName)&#123;</span><br><span class="line">            this.init();</span><br><span class="line">        CloudQueue queue1=null;</span><br><span class="line">        try&#123;</span><br><span class="line">            QueueMeta meta1 = new QueueMeta();</span><br><span class="line">            meta1.setQueueName(this.mnsPrefix+queueName);</span><br><span class="line">            meta1.setPollingWaitSeconds(30);</span><br><span class="line">            meta1.setMaxMessageSize(2048L);</span><br><span class="line">            queue1 = client.createQueue(meta1);</span><br><span class="line">            return queue1;</span><br><span class="line"></span><br><span class="line">        &#125;catch (Exception e)&#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">            return queue1;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public void deleteMessage(CloudQueue queue,String messageHandle)&#123;</span><br><span class="line">        this.init();</span><br><span class="line">        queue.deleteMessage(messageHandle);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public &lt;M&gt; void popMessageThread(String queueName,Object listener,Class&lt;M&gt; messageType)&#123;</span><br><span class="line"></span><br><span class="line">        MnsUtil mnsUtil=this;</span><br><span class="line">        try&#123;</span><br><span class="line">            this.createQueue(queueName);</span><br><span class="line">        &#125;catch (Exception e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        Runnable task=new Runnable() &#123;</span><br><span class="line">            @Override</span><br><span class="line">            public void run() &#123;</span><br><span class="line">                mnsUtil.popMessage(queueName,listener,messageType);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        Thread t=new Thread(task);</span><br><span class="line">        t.start();</span><br><span class="line">    &#125;</span><br><span class="line">    public &lt;M&gt; Message popMessage(String queueName,Object listener,Class&lt;M&gt; messageType)&#123;</span><br><span class="line">        this.init();</span><br><span class="line">        CloudQueue queue= client.getQueueRef(mnsPrefix+queueName);</span><br><span class="line"></span><br><span class="line">                while (true)&#123;</span><br><span class="line">                    try&#123;</span><br><span class="line">                        Message popMsg=null;</span><br><span class="line">                        try&#123;</span><br><span class="line">                            popMsg = queue.popMessage();</span><br><span class="line">                        &#125;catch (Exception e)&#123;</span><br><span class="line">                            logger.info(&quot;popMessage a message error&gt;&gt;&gt;&gt; currentTime&quot;+new Date());</span><br><span class="line">                            Thread.sleep(60000);</span><br><span class="line">                            e.printStackTrace();</span><br><span class="line">                        &#125;</span><br><span class="line">                        if(popMsg==null)&#123;</span><br><span class="line">                            continue;</span><br><span class="line">                        &#125;</span><br><span class="line">                        logger.info(&quot;read a message&gt;&gt;&gt;&gt;&quot;+popMsg.getMessageBody());</span><br><span class="line"></span><br><span class="line">                        Method method=listener.getClass().getMethod(&quot;process&quot;, messageType);</span><br><span class="line">                        M message=this.getMessageBody(popMsg.getMessageBody(),messageType);</span><br><span class="line">                        method.invoke(listener,message);</span><br><span class="line">                        String handle=popMsg.getReceiptHandle();</span><br><span class="line">                        queue.deleteMessage(handle);</span><br><span class="line">                    &#125;catch (Exception e)&#123;</span><br><span class="line">                        logger.error(&quot;error message&gt;&gt;&gt;&gt;&quot;+e.getMessage()+&quot;:&quot;+queueName);</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                        continue;</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    System.out.println(&quot;read a message&quot;);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">     public &lt;M&gt; M getMessageBody(String messageBody,Class&lt;M&gt; jsonType) throws Exception &#123;</span><br><span class="line">        Jackson2JsonObjectMapper jackson2JsonObjectMapper=new Jackson2JsonObjectMapper();</span><br><span class="line">        M messageObj=jackson2JsonObjectMapper.fromJson(messageBody,jsonType);</span><br><span class="line"></span><br><span class="line">        return messageObj;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public Message pushMessage(MnsMessage object) throws JsonProcessingException &#123;</span><br><span class="line">        if(object.getQueueName()==null)&#123;</span><br><span class="line">            logger.error(&quot;queue is null&quot;);</span><br><span class="line">            return null;</span><br><span class="line">        &#125;</span><br><span class="line">        this.init();</span><br><span class="line">        ObjectMapper mapper = new ObjectMapper();</span><br><span class="line">        CloudQueue queue= client.getQueueRef(mnsPrefix+MnsMessageListener.mnsQueueName);</span><br><span class="line">        String messageBody=  mapper.writeValueAsString(object);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        Message message = new Message();</span><br><span class="line">        message.setMessageBody(messageBody);</span><br><span class="line">        Message putMsg = queue.putMessage(message);</span><br><span class="line">        return putMsg;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    public static void main(String[] args)&#123;</span><br><span class="line">        MnsUtil mnsUtil=new MnsUtil();</span><br><span class="line">        System.out.println(&quot;over&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ImMessage imMessage=<span class="keyword">new</span> ImMessage();</span><br><span class="line"></span><br><span class="line">imMessage.setContent(p.getContent());</span><br><span class="line">imMessage.setFrom(<span class="string">"29"</span>);</span><br><span class="line">imMessage.setTo(userList);</span><br><span class="line">mnsUtil.pushMessage(imMessage);</span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/02/16/消息队列简单使用/" data-id="ckcc5iwmc004tq4uw1do2t3sn" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/消息队列/">消息队列</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-mysql/sql_ 关键字执行顺序" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/02/15/mysql/sql_ 关键字执行顺序/" class="article-date">
  <time datetime="2019-02-15T07:42:06.000Z" itemprop="datePublished">2019-02-15</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/02/15/mysql/sql_ 关键字执行顺序/">关键字执行顺序</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="mysql-关键字执行顺序"><a href="#mysql-关键字执行顺序" class="headerlink" title="mysql 关键字执行顺序"></a>mysql 关键字执行顺序</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">1.from</span><br><span class="line">2.on</span><br><span class="line">3.join</span><br><span class="line">4.where</span><br><span class="line">5.group by</span><br><span class="line">6.having</span><br><span class="line">7.select</span><br><span class="line">8.distinct</span><br><span class="line">9.union</span><br><span class="line">10.order by</span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/02/15/mysql/sql_ 关键字执行顺序/" data-id="ckcc5iwox007wq4uw3hjejadl" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mysql/">mysql</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-elasticsearch 模糊搜索" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/02/13/elasticsearch 模糊搜索/" class="article-date">
  <time datetime="2019-02-13T13:44:45.000Z" itemprop="datePublished">2019-02-13</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/02/13/elasticsearch 模糊搜索/">elasticsearch 模糊搜索</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="elasticsearch-模糊搜索"><a href="#elasticsearch-模糊搜索" class="headerlink" title="elasticsearch 模糊搜索"></a>elasticsearch 模糊搜索</h5><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">elastic.search.ex.index=xxx-exception</span><br><span class="line">elastic.search.story.index=xx-search</span><br><span class="line">elastic.search.host=xx.xx.62.93</span><br><span class="line">elastic.search.port=9200</span><br><span class="line">elastic.search.user=elastic:xxxxx</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">@Value</span>(<span class="string">"$&#123;elastic.search.host&#125;"</span>)</span><br><span class="line">String host;</span><br><span class="line"><span class="meta">@Value</span>(<span class="string">"$&#123;elastic.search.port&#125;"</span>)</span><br><span class="line">Integer port;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Value</span>(<span class="string">"$&#123;elastic.search.user&#125;"</span>)</span><br><span class="line">String elasticUser;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Value</span>(<span class="string">"/$&#123;elastic.search.ex.index&#125;/ex"</span>)</span><br><span class="line">String elasticIndex;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Value</span>(<span class="string">"$&#123;elastic.search.story.index&#125;"</span>)</span><br><span class="line">String elasticIndex_story;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"> RestClient restClient;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    Header header;</span><br><span class="line"></span><br><span class="line"><span class="comment">//    String elasticKey="/"+elasticIndex+"/user";</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> RestClient <span class="title">getClient</span><span class="params">()</span> </span>&#123;</span><br><span class="line"><span class="comment">//        if(restClient==null)&#123;&#125;</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">synchronized</span> (ElasticServiceImpl.class) &#123;</span><br><span class="line">            restClient = RestClient.builder(</span><br><span class="line">                    <span class="keyword">new</span> HttpHost(host, port, <span class="string">"http"</span>)</span><br><span class="line"></span><br><span class="line">            ).build();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> restClient;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Header <span class="title">getHeader</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(header==<span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (ElasticServiceImpl.class) &#123;</span><br><span class="line">                String token = Base64.getEncoder().encodeToString(elasticUser.getBytes());</span><br><span class="line">                header = <span class="keyword">new</span> BasicHeader(<span class="string">"Authorization"</span>, <span class="string">"Basic "</span> + token);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> header;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Page&lt;Map&gt; <span class="title">searchStoryNotNow</span><span class="params">(String content, <span class="keyword">int</span> pageNo, <span class="keyword">int</span> pageSize)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        restClient = <span class="keyword">this</span>.getClient();</span><br><span class="line"></span><br><span class="line">        Pageable pageable=<span class="keyword">new</span> PageRequest(pageNo,pageSize);</span><br><span class="line"></span><br><span class="line">        Map&lt;String,String&gt; params = Collections.emptyMap();</span><br><span class="line">        String jsonString = <span class="string">"&#123;\n"</span> +</span><br><span class="line">                <span class="string">" \"from\": "</span>+pageable.getOffset()+<span class="string">",\n"</span> +</span><br><span class="line">                <span class="string">" \"size\": "</span>+pageable.getPageSize()+<span class="string">",\n"</span> +</span><br><span class="line">                <span class="string">" \"query\": &#123;\n"</span> +</span><br><span class="line">                <span class="string">"    \"bool\": &#123;\n"</span> +</span><br><span class="line">                <span class="string">"        \"should\": [\n"</span> +</span><br><span class="line">                <span class="string">"             &#123; \"match\": &#123; \"name\": \""</span> + content + <span class="string">"\" &#125; &#125;,\n"</span> +</span><br><span class="line">                <span class="string">"             &#123; \"wildcard\": &#123; \"name\": \""</span>+<span class="string">"*"</span>+ content + <span class="string">"*"</span> + <span class="string">"\" &#125; &#125;,\n"</span> +</span><br><span class="line">                <span class="string">"             &#123; \"wildcard\": &#123;\"py_name\": \""</span> +<span class="string">"*"</span>+ content  +<span class="string">"*"</span>+ <span class="string">"\" &#125; &#125;\n"</span> +</span><br><span class="line">                <span class="string">"          ],\n"</span> +</span><br><span class="line">                <span class="string">"         \"must_not\": [\n"</span> +</span><br><span class="line">                <span class="string">"            &#123; \"match\": &#123; \"is_now\": \"1\" &#125; &#125;\n"</span> +</span><br><span class="line">                <span class="string">"           ]\n"</span> +</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">                <span class="string">"     &#125;\n"</span> +</span><br><span class="line"></span><br><span class="line">                <span class="string">"  &#125;\n"</span> +</span><br><span class="line">                <span class="comment">//如果自定义了排序,那么默认的_score排序就会失效</span></span><br><span class="line"><span class="comment">//                " \"sort\": [\n" +</span></span><br><span class="line"><span class="comment">//                "&#123;\"id\": \"desc\"&#125;\n" +</span></span><br><span class="line"><span class="comment">//                "]\n" +</span></span><br><span class="line">                <span class="string">"&#125;"</span>;</span><br><span class="line">        <span class="comment">//为HttpEntity指定ContentType非常重要，因为它将用于设置Content-Type请求头，以便Elasticsearch可以正确解析内容。</span></span><br><span class="line">        HttpEntity entity = <span class="keyword">new</span> NStringEntity(jsonString, ContentType.APPLICATION_JSON);</span><br><span class="line">        logger.info(<span class="string">"try get elastic_search_story_not_now"</span>);</span><br><span class="line">        Response response = restClient.performRequest(<span class="string">"GET"</span>, <span class="string">"/"</span> +elasticIndex_story +<span class="string">"/"</span> + <span class="string">"_search"</span>, params, entity);</span><br><span class="line">        logger.info(response.toString());</span><br><span class="line">        String resp= EntityUtils.toString(response.getEntity());</span><br><span class="line">        JsonObjectMapper jsonObjectMapper=<span class="keyword">new</span> Jackson2JsonObjectMapper();</span><br><span class="line">        ElasticResp&lt;Story&gt; elasticResp=(ElasticResp&lt;Story&gt;)jsonObjectMapper.fromJson(resp, ElasticResp.class);</span><br><span class="line"></span><br><span class="line">        logger.debug(response.toString());</span><br><span class="line">        List&lt;Story&gt; statusList=elasticResp.getHits().getSouceList();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        ElasticResp&lt;Map&gt; elasticResp2=(ElasticResp&lt;Map&gt;)jsonObjectMapper.fromJson(resp,ElasticResp.class);</span><br><span class="line">        List&lt;Map&gt; statusListMap=(List&lt;Map&gt;)elasticResp2.getHits().getSouceList();</span><br><span class="line">        Page&lt;Map&gt; userPage=<span class="keyword">new</span> PageImpl&lt;Map&gt;(statusListMap,pageable,elasticResp.getHits().getTotal());</span><br><span class="line"></span><br><span class="line">        restClient.close();</span><br><span class="line">        <span class="keyword">return</span> userPage;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/02/13/elasticsearch 模糊搜索/" data-id="ckcc5iwk1001nq4uwzxpg267l" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/elasticsearch/">elasticsearch</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-我的世界简单指令" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/02/04/我的世界简单指令/" class="article-date">
  <time datetime="2019-02-04T02:50:36.000Z" itemprop="datePublished">2019-02-04</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/02/04/我的世界简单指令/">我的世界指令</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="我的世界简单指令"><a href="#我的世界简单指令" class="headerlink" title="我的世界简单指令"></a>我的世界简单指令</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">/kill  自杀</span><br><span class="line"></span><br><span class="line">/gamerule keepInventory true 死亡掉落</span><br><span class="line"></span><br><span class="line">/spawnpoint  重生地</span><br></pre></td></tr></table></figure>
<hr>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br></pre></td><td class="code"><pre><span class="line">/give 蓝色小火 Obsidian 64   黑曜石  Obsidian</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">铁矿石  iron_ore</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Stone 石头</span><br><span class="line">Dirt 泥土</span><br><span class="line">Cobblestone 原石</span><br><span class="line">Wood 木板</span><br><span class="line">Sapling 树苗</span><br><span class="line">Water 水</span><br><span class="line">Lava 岩浆</span><br><span class="line">Sand 沙子</span><br><span class="line">Gravel 沙砾</span><br><span class="line">Gold Ore 金矿</span><br><span class="line">Iron Ore 铁矿</span><br><span class="line">Log 木头</span><br><span class="line">Red Log 红木</span><br><span class="line">Birch Log 白杨木</span><br><span class="line">Leaves 树叶</span><br><span class="line">Sponge 海绵</span><br><span class="line">Glass 玻璃</span><br><span class="line">Lapis Lazuli Ore 青金石矿</span><br><span class="line">Lapis Lazuli 青金石</span><br><span class="line">Dispenser 发射器</span><br><span class="line">Sandstone 沙石</span><br><span class="line">Note Block 音符盒</span><br><span class="line">White Wool 白羊毛</span><br><span class="line">Orange Wool 橙羊毛</span><br><span class="line">Magenta Wool 淡紫羊毛</span><br><span class="line">Light Blue Wool 淡蓝羊毛</span><br><span class="line">Yellow Wool 黄羊毛</span><br><span class="line">Light Green Wool 浅绿羊毛</span><br><span class="line">pink Wool	粉红羊毛</span><br><span class="line">Gray Wool 灰羊毛</span><br><span class="line">Light Gray Wool 浅灰羊毛</span><br><span class="line">Cyan Wool</span><br><span class="line">urple Wool	紫羊毛</span><br><span class="line">Blue Wool 蓝羊毛</span><br><span class="line">Brown Wool 棕羊毛</span><br><span class="line">Dark Green Wool 墨绿羊毛</span><br><span class="line">Red Wool 红羊毛</span><br><span class="line">Black Wool 黑羊毛</span><br><span class="line">Yellow Flower 黄花</span><br><span class="line">Red Rose 红玫瑰</span><br><span class="line">Brown Mushroom 棕蘑菇</span><br><span class="line">Red Mushroom 红蘑菇</span><br><span class="line">Gold Block	黄金块</span><br><span class="line">Iron Block	铁块</span><br><span class="line">Stone Slab	石板</span><br><span class="line">Sandstone Slab	砂岩板</span><br><span class="line">Wooden Slab	木制板</span><br><span class="line">Cobblestone Slab	鹅卵石板</span><br><span class="line">Brick	砖</span><br><span class="line">TNT	TNT</span><br><span class="line">Bookcase	书架</span><br><span class="line">Mossy Cobblestone	长满青苔</span><br><span class="line">的鹅卵石</span><br><span class="line">Obsidian	黑曜岩</span><br><span class="line">Torch	火炬</span><br><span class="line">Wooden Stairs	木楼梯</span><br><span class="line">Chest	胸部</span><br><span class="line">Diamond Block	钻石块</span><br><span class="line">Workbench	工作台</span><br><span class="line">Furnace	炉</span><br><span class="line">Ladder	梯子</span><br><span class="line">Minecart Tracks	矿车轨道</span><br><span class="line">Cobblestone Stairs	鹅卵石楼</span><br><span class="line">梯</span><br><span class="line">Lever	杠杆</span><br><span class="line">Stone Pressure Plate	石头压板</span><br><span class="line">Wooden Pressure Plate	木制压板</span><br><span class="line">Redstone Torch	红石火把</span><br><span class="line">Stone Button	石头按钮</span><br><span class="line">Ice	冰</span><br><span class="line">Snow Block	雪块</span><br><span class="line">Cactus	仙人掌</span><br><span class="line">Jukebox	自动点唱机</span><br><span class="line">Fence	栅栏</span><br><span class="line">umpkin	南瓜子仁</span><br><span class="line">Red Mossy Cobblestone	红色长满</span><br><span class="line">青苔的鹅卵石</span><br><span class="line">Slow Sand	慢砂</span><br><span class="line">Lightstone Ore	浅石色矿</span><br><span class="line">Jack-O-Lantern	杰克灯笼</span><br><span class="line">Iron Spade	铁铲</span><br><span class="line">Iron Pickaxe	铁锄</span><br><span class="line">Iron Axe	铁斧</span><br><span class="line">Flint and Steel	打火石</span><br><span class="line">Red Apple	红苹果</span><br><span class="line">Bow	弓</span><br><span class="line">Arrow	箭头</span><br><span class="line">Coal	煤炭</span><br><span class="line">Diamond	钻石</span><br><span class="line">Iron Ingot	铁锭</span><br><span class="line">Gold Ingot	金元宝</span><br><span class="line">Iron Sword	铁剑</span><br><span class="line">Wooden Sword	木剑</span><br><span class="line">Wooden Spade	木铲</span><br><span class="line">Wooden Pickaxe	木柄鹤嘴锄</span><br><span class="line">Wooden Axe	木斧</span><br><span class="line">Stone Sword	石剑</span><br><span class="line">Stone Spade	石锹</span><br><span class="line">Stone Pickaxe	石镐</span><br><span class="line">Stone Axe	石斧头</span><br><span class="line">Diamond Sword	钻石剑</span><br><span class="line">Diamond Spade	钻石锹</span><br><span class="line">Diamond Pickaxe	钻石镐</span><br><span class="line">Diamond Axe	钻石斧</span><br><span class="line">Stick	棍子</span><br><span class="line">Bowl	碗</span><br><span class="line">Mushroom Soup	蘑菇汤</span><br><span class="line">Gold Sword	金剑</span><br><span class="line">Gold Spade	金锹</span><br><span class="line">Gold Pickaxe	金镐</span><br><span class="line">Gold Axe	金斧子</span><br><span class="line">String	线</span><br><span class="line">Feather	羽毛</span><br><span class="line">Gunpowder	火药</span><br><span class="line">Wooden Hoe	木锄</span><br><span class="line">Stone Hoe	石锄</span><br><span class="line">Iron Hoe	铁锄头</span><br><span class="line">Diamond Hoe	钻石锄头</span><br><span class="line">Gold Hoe	金锄头</span><br><span class="line">Seeds	种子</span><br><span class="line">Wheat	小麦</span><br><span class="line">Bread	面包</span><br><span class="line">Leather Helmet	皮革头盔</span><br><span class="line">Leather Chestplate</span><br><span class="line">Leather Pants	皮裤</span><br><span class="line">Leather Boots	皮靴子</span><br><span class="line">Iron Helmet	铁头盔</span><br><span class="line">Iron Chestplate	铁护胸</span><br><span class="line">Iron Pants	铁裤</span><br><span class="line">Iron Boots	铁靴</span><br><span class="line">Diamond Helmet	钻石头盔</span><br><span class="line">Diamond Chestplate</span><br><span class="line">Diamond Pants	钻石的裤子</span><br><span class="line">Diamond Boots	钻石的靴子</span><br><span class="line">Gold Helmet	金头盔</span><br><span class="line">Gold Chestplate	金护胸</span><br><span class="line">Gold Pants	黄金的裤子</span><br><span class="line">Gold Boots	金靴子</span><br><span class="line">Flint	燧石</span><br><span class="line">ork	兽人</span><br><span class="line">Grilled Pork	烤的猪肉</span><br><span class="line">aintings	油画</span><br><span class="line">Golden Apple	金苹果</span><br><span class="line">Sign	标志</span><br><span class="line">Wooden Door	木门</span><br><span class="line">Bucket	桶</span><br><span class="line">Water Bucket	水桶</span><br><span class="line">Lava Bucket	岩浆桶</span><br><span class="line">Mine Cart	矿山车</span><br><span class="line">Saddle	马鞍</span><br><span class="line">Iron Door	铁门</span><br><span class="line">Redstone	红石</span><br><span class="line">Snowball	雪球</span><br><span class="line">Boat	小船</span><br><span class="line">Leather	皮革</span><br><span class="line">Milk Bucket	牛奶桶</span><br><span class="line">Clay Brick	粘土砖</span><br><span class="line">Clay Balls	粘土球</span><br><span class="line">Reed	芦苇</span><br><span class="line">aper	野猪</span><br><span class="line">Book	本书</span><br><span class="line">Slime Ball	泥球</span><br><span class="line">Storage Minecart</span><br><span class="line">owered Minecart	动力矿车</span><br><span class="line">Egg	鸡蛋</span><br><span class="line">Compass	指南针</span><br><span class="line">Fishing Rod	钓鱼杆</span><br><span class="line">Watch	手表</span><br><span class="line">Lightstone Dust	星彩蓝宝石</span><br><span class="line">Raw Fish	生鱼</span><br><span class="line">Cooked Fish	煮熟的鱼</span><br><span class="line">Ink Sac Dye	墨囊染料</span><br><span class="line">Rose Red Dye	玫瑰红染料</span><br><span class="line">Cactus Green Dye</span><br><span class="line">Cocoa Beans Dye	可可豆染料</span><br><span class="line">Lapis Lazuli Dye</span><br><span class="line">urple Dye	紫色染料</span><br><span class="line">Cyan Dye	青色染料</span><br><span class="line">Light Gray Dye	淡灰色染料</span><br><span class="line">Gray Dye	灰色染料</span><br><span class="line">ink Dye	染料墨水</span><br><span class="line">Lime Dye	石灰染料</span><br><span class="line">Dandelion Yellow Dye</span><br><span class="line">Light Blue Dye	淡蓝色染料</span><br><span class="line">MagentaDye	品红色染料</span><br><span class="line">Orange Dye	橙色染料</span><br><span class="line">Bone Meal Dye	肉骨粉染料</span><br><span class="line">Bone	骨</span><br><span class="line">Sugar	糖</span><br><span class="line">Cake	蛋糕</span><br><span class="line">Gold Record	金唱片</span><br><span class="line">Green RecordIf	绿色记录如果</span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/02/04/我的世界简单指令/" data-id="ckcc5iwm3004eq4uwtwak82pt" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/我的世界/">我的世界</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-http/http_Java信任SSL证书" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/01/28/http/http_Java信任SSL证书/" class="article-date">
  <time datetime="2019-01-28T10:21:46.000Z" itemprop="datePublished">2019-01-28</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/01/28/http/http_Java信任SSL证书/">Java 信任SSL证书</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="Java-信任所有SSL证书-解决PKIX-path-building-failed问题"><a href="#Java-信任所有SSL证书-解决PKIX-path-building-failed问题" class="headerlink" title="Java 信任所有SSL证书(解决PKIX path building failed问题)"></a>Java 信任所有SSL证书(解决PKIX path building failed问题)</h5><p><a href="http://javaweb.org/?p=1237" target="_blank" rel="noopener">http://javaweb.org/?p=1237</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target</span><br><span class="line">    at sun.security.ssl.Alerts.getSSLException(Alerts.java:<span class="number">192</span>)</span><br><span class="line">    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:<span class="number">1884</span>)</span><br><span class="line">    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:<span class="number">276</span>)</span><br><span class="line">    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:<span class="number">270</span>)</span><br><span class="line">    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:<span class="number">1341</span>)</span><br><span class="line">    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:<span class="number">153</span>)</span><br><span class="line">    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:<span class="number">868</span>)</span><br><span class="line">    at sun.security.ssl.Handshaker.process_record(Handshaker.java:<span class="number">804</span>)</span><br><span class="line">    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:<span class="number">1016</span>)</span><br><span class="line">    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:<span class="number">1312</span>)</span><br><span class="line">    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:<span class="number">1339</span>)</span><br><span class="line">    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:<span class="number">1323</span>)</span><br><span class="line">    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:<span class="number">563</span>)</span><br><span class="line">    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:<span class="number">185</span>)</span><br><span class="line">    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:<span class="number">1300</span>)</span><br><span class="line">    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:<span class="number">254</span>)</span><br><span class="line">    at SslTest.getRequest(SslTest.java:<span class="number">16</span>)</span><br><span class="line">    at SslTest.main(SslTest.java:<span class="number">40</span>)</span><br><span class="line">Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target</span><br><span class="line">    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:<span class="number">385</span>)</span><br><span class="line">    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:<span class="number">230</span>)</span><br><span class="line">    at sun.security.validator.Validator.validate(Validator.java:<span class="number">260</span>)</span><br><span class="line">    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:<span class="number">326</span>)</span><br><span class="line">    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:<span class="number">231</span>)</span><br><span class="line">    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:<span class="number">126</span>)</span><br><span class="line">    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:<span class="number">1323</span>)</span><br><span class="line">    ... <span class="number">13</span> more</span><br><span class="line">Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target</span><br><span class="line">    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:<span class="number">196</span>)</span><br><span class="line">    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:<span class="number">268</span>)</span><br><span class="line">    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:<span class="number">380</span>)</span><br><span class="line">    ... <span class="number">19</span> more</span><br></pre></td></tr></table></figure>
<p>解决办法：</p>
<p>1、导入证书到本地证书库</p>
<p>2、信任所有SSL证书</p>
<p>最好的解决办法或许是信任所有SSL证书，因为某些时候不能每次都手动的导入证书非常麻烦。现在封装了个方法，在连接openConnection的时候忽略掉证书就行了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">SslUtils.ignoreSsl();</span><br></pre></td></tr></table></figure>
<p><strong>SslUtils.java:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.security.cert.CertificateException;</span><br><span class="line"><span class="keyword">import</span> java.security.cert.X509Certificate;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.HostnameVerifier;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.HttpsURLConnection;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.SSLContext;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.SSLSession;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.TrustManager;</span><br><span class="line"><span class="keyword">import</span> javax.net.ssl.X509TrustManager;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SslUtils</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">trustAllHttpsCertificates</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        TrustManager[] trustAllCerts = <span class="keyword">new</span> TrustManager[<span class="number">1</span>];</span><br><span class="line">        TrustManager tm = <span class="keyword">new</span> miTM();</span><br><span class="line">        trustAllCerts[<span class="number">0</span>] = tm;</span><br><span class="line">        SSLContext sc = SSLContext.getInstance(<span class="string">"SSL"</span>);</span><br><span class="line">        sc.init(<span class="keyword">null</span>, trustAllCerts, <span class="keyword">null</span>);</span><br><span class="line">        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">miTM</span> <span class="keyword">implements</span> <span class="title">TrustManager</span>,<span class="title">X509TrustManager</span> </span>&#123;</span><br><span class="line">        <span class="keyword">public</span> X509Certificate[] getAcceptedIssuers() &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isServerTrusted</span><span class="params">(X509Certificate[] certs)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isClientTrusted</span><span class="params">(X509Certificate[] certs)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkServerTrusted</span><span class="params">(X509Certificate[] certs, String authType)</span></span></span><br><span class="line"><span class="function">                <span class="keyword">throws</span> CertificateException </span>&#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkClientTrusted</span><span class="params">(X509Certificate[] certs, String authType)</span></span></span><br><span class="line"><span class="function">                <span class="keyword">throws</span> CertificateException </span>&#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 忽略HTTPS请求的SSL证书，必须在openConnection之前调用</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ignoreSsl</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        HostnameVerifier hv = <span class="keyword">new</span> HostnameVerifier() &#123;</span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">verify</span><span class="params">(String urlHostName, SSLSession session)</span> </span>&#123;</span><br><span class="line">                System.out.println(<span class="string">"Warning: URL Host: "</span> + urlHostName + <span class="string">" vs. "</span> + session.getPeerHost());</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        trustAllHttpsCertificates();</span><br><span class="line">        HttpsURLConnection.setDefaultHostnameVerifier(hv);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>SslTest.java:</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.OutputStreamWriter;</span><br><span class="line"><span class="keyword">import</span> java.net.URL;</span><br><span class="line"><span class="keyword">import</span> java.net.URLConnection;</span><br><span class="line"><span class="keyword">import</span> org.apache.commons.io.IOUtils;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SslTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getRequest</span><span class="params">(String url,<span class="keyword">int</span> timeOut)</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        URL u = <span class="keyword">new</span> URL(url);</span><br><span class="line">        <span class="keyword">if</span>(<span class="string">"https"</span>.equalsIgnoreCase(u.getProtocol()))&#123;</span><br><span class="line">            SslUtils.ignoreSsl();</span><br><span class="line">        &#125;</span><br><span class="line">        URLConnection conn = u.openConnection();</span><br><span class="line">        conn.setConnectTimeout(timeOut);</span><br><span class="line">        conn.setReadTimeout(timeOut);</span><br><span class="line">        <span class="keyword">return</span> IOUtils.toString(conn.getInputStream());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">postRequest</span><span class="params">(String urlAddress,String args,<span class="keyword">int</span> timeOut)</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        URL url = <span class="keyword">new</span> URL(urlAddress);</span><br><span class="line">        <span class="keyword">if</span>(<span class="string">"https"</span>.equalsIgnoreCase(url.getProtocol()))&#123;</span><br><span class="line">            SslUtils.ignoreSsl();</span><br><span class="line">        &#125;</span><br><span class="line">        URLConnection u = url.openConnection();</span><br><span class="line">        u.setDoInput(<span class="keyword">true</span>);</span><br><span class="line">        u.setDoOutput(<span class="keyword">true</span>);</span><br><span class="line">        u.setConnectTimeout(timeOut);</span><br><span class="line">        u.setReadTimeout(timeOut);</span><br><span class="line">        OutputStreamWriter osw = <span class="keyword">new</span> OutputStreamWriter(u.getOutputStream(), <span class="string">"UTF-8"</span>);</span><br><span class="line">        osw.write(args);</span><br><span class="line">        osw.flush();</span><br><span class="line">        osw.close();</span><br><span class="line">        u.getOutputStream();</span><br><span class="line">        <span class="keyword">return</span> IOUtils.toString(u.getInputStream());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            SslTest st = <span class="keyword">new</span> SslTest();</span><br><span class="line">            String a = st.getRequest(<span class="string">"https://xxx.com/login.action"</span>, <span class="number">3000</span>);</span><br><span class="line">            System.out.println(a);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/01/28/http/http_Java信任SSL证书/" data-id="ckcc5iwnt005zq4uwymbtm2il" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Http/">Http</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-Spring Boot缓存注解" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/01/24/Spring Boot缓存注解/" class="article-date">
  <time datetime="2019-01-24T06:19:51.000Z" itemprop="datePublished">2019-01-24</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/01/24/Spring Boot缓存注解/">Spring Boot缓存注解</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h5 id="Spring-Boot缓存注解"><a href="#Spring-Boot缓存注解" class="headerlink" title="Spring Boot缓存注解"></a>Spring Boot缓存注解</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">Cache注解详解</span><br><span class="line">@CacheConfig：主要用于配置该类中会用到的一些共用的缓存配置。在这里@CacheConfig(cacheNames = &quot;users&quot;)：配置了该数据访问对象中返回的内容将存储于名为users的缓存对象中，我们也可以不使用该注解，直接通过@Cacheable自己配置缓存集的名字来定义。</span><br><span class="line"></span><br><span class="line">@Cacheable：配置了findByName函数的返回值将被加入缓存。同时在查询时，会先从缓存中获取，若不存在才再发起对数据库的访问。该注解主要有下面几个参数：</span><br><span class="line"></span><br><span class="line">value、cacheNames：两个等同的参数（cacheNames为Spring 4新增，作为value的别名），用于指定缓存存储的集合名。由于Spring 4中新增了@CacheConfig，因此在Spring 3中原本必须有的value属性，也成为非必需项了</span><br><span class="line">key：缓存对象存储在Map集合中的key值，非必需，缺省按照函数的所有参数组合作为key值，若自己配置需使用SpEL表达式，比如：@Cacheable(key = &quot;#p0&quot;)：使用函数第一个参数作为缓存的key值，更多关于SpEL表达式的详细内容可参考官方文档</span><br><span class="line">condition：缓存对象的条件，非必需，也需使用SpEL表达式，只有满足表达式条件的内容才会被缓存，比如：@Cacheable(key = &quot;#p0&quot;, condition = &quot;#p0.length() &lt; 3&quot;)，表示只有当第一个参数的长度小于3的时候才会被缓存，若做此配置上面的AAA用户就不会被缓存，读者可自行实验尝试。</span><br><span class="line">unless：另外一个缓存条件参数，非必需，需使用SpEL表达式。它不同于condition参数的地方在于它的判断时机，该条件是在函数被调用之后才做判断的，所以它可以通过对result进行判断。</span><br><span class="line">keyGenerator：用于指定key生成器，非必需。若需要指定一个自定义的key生成器，我们需要去实现org.springframework.cache.interceptor.KeyGenerator接口，并使用该参数来指定。需要注意的是：该参数与key是互斥的</span><br><span class="line">cacheManager：用于指定使用哪个缓存管理器，非必需。只有当有多个时才需要使用</span><br><span class="line">cacheResolver：用于指定使用那个缓存解析器，非必需。需通过org.springframework.cache.interceptor.CacheResolver接口来实现自己的缓存解析器，并用该参数指定。</span><br><span class="line">除了这里用到的两个注解之外，还有下面几个核心注解：</span><br><span class="line"></span><br><span class="line">@CachePut：配置于函数上，能够根据参数定义条件来进行缓存，它与@Cacheable不同的是，它每次都会真是调用函数，所以主要用于数据新增和修改操作上。它的参数与@Cacheable类似，具体功能可参考上面对@Cacheable参数的解析</span><br><span class="line">@CacheEvict：配置于函数上，通常用在删除方法上，用来从缓存中移除相应数据。除了同@Cacheable一样的参数之外，它还有下面两个参数：</span><br><span class="line">allEntries：非必需，默认为false。当为true时，会移除所有数据</span><br><span class="line">beforeInvocation：非必需，默认为false，会在调用方法之后移除数据。当为true时，会在调用方法之前移除数据。</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Cacheable</span>(cacheNames =<span class="string">"ktx_fudai_user_"</span>,key = <span class="string">"'ktx_fudai_user_'+#root.args[0]"</span> )</span><br><span class="line"><span class="function">ActivityUser <span class="title">findActivityUserById</span><span class="params">(Integer id)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Cacheable</span>(cacheNames =<span class="string">"ktx_fudai_user_"</span>,key = <span class="string">"'ktx_fudai_user_'+#root.args[0]"</span> )</span><br><span class="line"><span class="function">ActivityUser <span class="title">findActivityUserByUnionId</span><span class="params">(String unionId)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@Caching</span>(evict = &#123;</span><br><span class="line">        <span class="meta">@CacheEvict</span>(cacheNames = <span class="string">"ktx_fudai_user_"</span>,key = <span class="string">"'ktx_fudai_user_'+#root.args[0].id"</span>),</span><br><span class="line">        <span class="meta">@CacheEvict</span>(cacheNames = <span class="string">"ktx_fudai_user_"</span>,key = <span class="string">"'ktx_fudai_user_'+#root.args[0].unionId"</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="function">ActivityUser <span class="title">save</span><span class="params">(ActivityUser activityUser)</span></span>;</span><br></pre></td></tr></table></figure>
<p><strong>@Cacheable 作用和配置方法</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>解释</th>
<th>示例</th>
</tr>
</thead>
<tbody>
<tr>
<td>value</td>
<td>缓存的名称，在 spring 配置文件中定义，必须指定至少一个</td>
<td>@Cacheable(value=”testcache”,key=”#userName”)</td>
</tr>
<tr>
<td>key</td>
<td>缓存的 key，可以为空，如果指定要按照 SpEL 表达式编写，如果不指定，则缺省按照方法的所有参数进行组合</td>
<td>@Cacheable(value=”testcache”,key=”#userName”)</td>
</tr>
<tr>
<td>condition</td>
<td>缓存的条件，可以为空，使用 SpEL 编写，返回 true 或者 false，只有为 true 才进行缓存</td>
<td>@Cacheable(value=”testcache”,condition=”#userName.length()&gt;2”)</td>
</tr>
</tbody>
</table>
<h5 id="CachePut"><a href="#CachePut" class="headerlink" title="@CachePut"></a><strong>@CachePut</strong></h5><p>@CachePut 的作用 主要针对方法配置，能够根据方法的请求参数对其结果进行缓存，和 @Cacheable 不同的是，它每次都会触发真实方法的调用</p>
<p><strong>@CachePut 作用和配置方法</strong><br>参数 | 解释 | 示例<br>—|—|—<br>value |     缓存的名称，在 spring 配置文件中定义，必须指定至少一个 | @CachePut(value=”my cache”)<br>key | 缓存的 key，可以为空，如果指定要按照 SpEL 表达式编写，如果不指定，则缺省按照方法的所有参数进行组合 | @CachePut(value=”testcache”,key=”#userName”)<br>condition | 缓存的条件，可以为空，使用 SpEL 编写，返回 true 或者 false，只有为 true 才进行缓存 | @CachePut(value=”testcache”,condition=”#userName.length()&gt;2”)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CachePut</span>(value=<span class="string">"accountCache"</span>,key=<span class="string">"#account.getName()"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> Account <span class="title">updateAccount</span><span class="params">(Account account)</span> </span>&#123; </span><br><span class="line">   <span class="keyword">return</span> updateDB(account); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="CacheEvict"><a href="#CacheEvict" class="headerlink" title="@CacheEvict"></a>@CacheEvict</h5><p>@CachEvict 的作用 主要针对方法配置，能够根据一定的条件对缓存进行清空</p>
<p><strong>@CacheEvict 作用和配置方法</strong><br>参数 | 解释 | 示例<br>—|—|—<br>value |     缓存的名称，在 spring 配置文件中定义，必须指定至少一个 | @CachePut(value=”my cache”)<br>key | 缓存的 key，可以为空，如果指定要按照 SpEL 表达式编写，如果不指定，则缺省按照方法的所有参数进行组合 | @CachePut(value=”testcache”,key=”#userName”)<br>condition | 缓存的条件，可以为空，使用 SpEL 编写，返回 true 或者 false，只有为 true 才进行缓存 | @CachePut(value=”testcache”,condition=”#userName.length()&gt;2”)<br>allEntries |     是否清空所有缓存内容，缺省为 false，如果指定为 true，则方法调用后将立即清空所有缓存 | @CachEvict(value=”testcache”,allEntries=true)<br>beforeInvocation | 是否在方法执行前就清空，缺省为 false，如果指定为 true，则在方法还没有执行的时候就清空缓存，缺省情况下，如果方法执行抛出异常，则不会清空缓存 | @CachEvict(value=”testcache”，beforeInvocation=true)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CacheEvict</span>(value=<span class="string">"accountCache"</span>,key=<span class="string">"#account.getName()"</span>)<span class="comment">// 清空accountCache 缓存  </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateAccount</span><span class="params">(Account account)</span> </span>&#123;</span><br><span class="line">     updateDB(account); </span><br><span class="line">&#125; </span><br><span class="line"></span><br><span class="line"><span class="meta">@CacheEvict</span>(value=<span class="string">"accountCache"</span>,allEntries=<span class="keyword">true</span>)<span class="comment">// 清空accountCache 缓存</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">reload</span><span class="params">()</span> </span>&#123;</span><br><span class="line">     reloadAll()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Cacheable</span>(value=<span class="string">"accountCache"</span>,condition=<span class="string">"#userName.length() &lt;=4"</span>)<span class="comment">// 缓存名叫 accountCache </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Account <span class="title">getAccountByName</span><span class="params">(String userName)</span> </span>&#123; </span><br><span class="line"> <span class="comment">// 方法内部实现不考虑缓存逻辑，直接实现业务</span></span><br><span class="line"> <span class="keyword">return</span> getFromDB(userName); </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="条件缓存"><a href="#条件缓存" class="headerlink" title="条件缓存"></a>条件缓存</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//@Cacheable将在执行方法之前( #result还拿不到返回值)判断condition，如果返回true，则查缓存； </span></span><br><span class="line"><span class="meta">@Cacheable</span>(value = <span class="string">"user"</span>, key = <span class="string">"#id"</span>, condition = <span class="string">"#id lt 10"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">conditionFindById</span><span class="params">(<span class="keyword">final</span> Long id)</span>  </span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="comment">//@CachePut将在执行完方法后（#result就能拿到返回值了）判断condition，如果返回true，则放入缓存； </span></span></span><br><span class="line"><span class="function">@<span class="title">CachePut</span><span class="params">(value = <span class="string">"user"</span>, key = <span class="string">"#id"</span>, condition = <span class="string">"#result.username ne 'zhang'"</span>)</span>  </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">conditionSave</span><span class="params">(<span class="keyword">final</span> User user)</span>   </span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="comment">//@CachePut将在执行完方法后（#result就能拿到返回值了）判断unless，如果返回false，则放入缓存；（即跟condition相反）</span></span></span><br><span class="line"><span class="function">@<span class="title">CachePut</span><span class="params">(value = <span class="string">"user"</span>, key = <span class="string">"#user.id"</span>, unless = <span class="string">"#result.username eq 'zhang'"</span>)</span></span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">conditionSave2</span><span class="params">(<span class="keyword">final</span> User user)</span>   </span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="comment">//@CacheEvict， beforeInvocation=false表示在方法执行之后调用（#result能拿到返回值了）；且判断condition，如果返回true，则移除缓存；</span></span></span><br><span class="line"><span class="function">@<span class="title">CacheEvict</span><span class="params">(value = <span class="string">"user"</span>, key = <span class="string">"#user.id"</span>, beforeInvocation = <span class="keyword">false</span>, condition = <span class="string">"#result.username ne 'zhang'"</span>)</span>  </span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">conditionDelete</span><span class="params">(<span class="keyword">final</span> User user)</span></span></span><br></pre></td></tr></table></figure>
<p><strong>@Caching</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Caching</span>(put = &#123;</span><br><span class="line"><span class="meta">@CachePut</span>(value = <span class="string">"user"</span>, key = <span class="string">"#user.id"</span>),</span><br><span class="line"><span class="meta">@CachePut</span>(value = <span class="string">"user"</span>, key = <span class="string">"#user.username"</span>),</span><br><span class="line"><span class="meta">@CachePut</span>(value = <span class="string">"user"</span>, key = <span class="string">"#user.email"</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">save</span><span class="params">(User user)</span> </span>&#123;</span><br></pre></td></tr></table></figure>
<h5 id="SpEL上下文数据"><a href="#SpEL上下文数据" class="headerlink" title="SpEL上下文数据"></a>SpEL上下文数据</h5><table>
<thead>
<tr>
<th>名称</th>
<th>位置</th>
<th>描述</th>
<th>示例</th>
</tr>
</thead>
<tbody>
<tr>
<td>methodName</td>
<td>root对象</td>
<td>当前被调用的方法名</td>
<td>root.methodName</td>
</tr>
<tr>
<td>method</td>
<td>root对象</td>
<td>当前被调用的方法</td>
<td>root.methodName</td>
</tr>
<tr>
<td>target</td>
<td>root对象</td>
<td>当前被调用的目标对象</td>
<td>root.target</td>
</tr>
<tr>
<td>targetClass</td>
<td>root对象</td>
<td>当前被调用的目标对象类</td>
<td>root.targetClass</td>
</tr>
<tr>
<td>args</td>
<td>root对象</td>
<td>当前被调用的方法的参数列表</td>
<td>root.args[0]</td>
</tr>
<tr>
<td>caches</td>
<td>root对象</td>
<td>当前方法调用使用的缓存列表（如@Cacheable(value={“cache1”, “cache2”})），则有两个cache</td>
<td>root.caches[0].name</td>
</tr>
<tr>
<td>argument</td>
<td>执行上下文</td>
<td>当前被调用的方法的参数，如findById(Long id)，我们可以通过#id拿到参数</td>
<td>user.id</td>
</tr>
<tr>
<td>result</td>
<td>执行上下文</td>
<td>方法执行后的返回值（仅当方法执行之后的判断有效，如‘unless’，’cache evict’的beforeInvocation=false）</td>
<td>result</td>
</tr>
</tbody>
</table>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@CacheEvict</span>(value = <span class="string">"user"</span>, key = <span class="string">"#user.id"</span>, condition = <span class="string">"#root.target.canCache() and #root.caches[0].get(#user.id).get().username ne #user.username"</span>, beforeInvocation = <span class="keyword">true</span>)  </span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">conditionUpdate</span><span class="params">(User user)</span></span></span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/01/24/Spring Boot缓存注解/" data-id="ckcc5iwj9000uq4uws0acmwmx" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/springboot/">springboot</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-mysql/sql_数据库性能优化" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/01/14/mysql/sql_数据库性能优化/" class="article-date">
  <time datetime="2019-01-14T02:43:14.000Z" itemprop="datePublished">2019-01-14</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/01/14/mysql/sql_数据库性能优化/">数据库-性能优化</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="1、-为什么要进行数据库优化？"><a href="#1、-为什么要进行数据库优化？" class="headerlink" title="1、   为什么要进行数据库优化？"></a>1、   为什么要进行数据库优化？</h2><h3 id="1-1、-避免网站页面出现访问错误"><a href="#1-1、-避免网站页面出现访问错误" class="headerlink" title="1.1、 避免网站页面出现访问错误"></a>1.1、 避免网站页面出现访问错误</h3><p>由于数据库连接timeout产生页面5xx错误</p>
<p>由于慢查询造成页面无法加载</p>
<p>由于阻塞造成数据无法提交</p>
<h3 id="1-2、-增加数据库的稳定性"><a href="#1-2、-增加数据库的稳定性" class="headerlink" title="1.2、 增加数据库的稳定性"></a>1.2、 增加数据库的稳定性</h3><p>很多数据库问题都是由于低效的查询引起的</p>
<h3 id="1-3、-优化用户体验"><a href="#1-3、-优化用户体验" class="headerlink" title="1.3、 优化用户体验"></a>1.3、 优化用户体验</h3><p>流畅页面的访问速度</p>
<p>良好的网站功能体验</p>
<h2 id="2、mysql数据库优化"><a href="#2、mysql数据库优化" class="headerlink" title="2、mysql数据库优化"></a>2、mysql数据库优化</h2><p>可以从哪几个方面进行数据库的优化？如下图所示：</p>
<p><img src="file:///C:/Users/Deborah/AppData/Local/Temp/msohtmlclip1/01/clip_image002.png" alt=""></p>
<h3 id="2-1、-SQL及索引优化"><a href="#2-1、-SQL及索引优化" class="headerlink" title="2.1、 SQL及索引优化"></a>2.1、 SQL及索引优化</h3><p>​    根据需求写出良好的SQL，并创建有效的索引，实现某一种需求可以多种写法，这时候我们就要选择一种效率最高的写法。这个时候就要了解sql优化</p>
<h3 id="2-2、-数据库表结构优化"><a href="#2-2、-数据库表结构优化" class="headerlink" title="2.2、 数据库表结构优化"></a>2.2、 数据库表结构优化</h3><p>根据数据库的范式，设计表结构，表结构设计的好直接关系到写SQL语句。</p>
<h3 id="2-3、-系统配置优化"><a href="#2-3、-系统配置优化" class="headerlink" title="2.3、 系统配置优化"></a>2.3、 系统配置优化</h3><p>大多数运行在Linux机器上，如tcp连接数的限制、打开文件数的限制、安全性的限制，因此我们要对这些配置进行相应的优化。</p>
<h3 id="2-4、硬件配置优化"><a href="#2-4、硬件配置优化" class="headerlink" title="2.4、硬件配置优化"></a>2.4、硬件配置优化</h3><p>选择适合数据库服务的cpu，更快的IO，更高的内存；cpu并不是越多越好，某些数据库版本有最大的限制，IO操作并不是减少阻塞。</p>
<p>注：通过上图可以看出，该金字塔中，优化的成本从下而上逐渐增高，而优化的效果会逐渐降低。</p>
<h2 id="3、SQL及索引优化"><a href="#3、SQL及索引优化" class="headerlink" title="3、SQL及索引优化"></a>3、SQL及索引优化</h2><h3 id="3-1、查看mysql的版本"><a href="#3-1、查看mysql的版本" class="headerlink" title="3.1、查看mysql的版本"></a>3.1、查看mysql的版本</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">select @@version;</span><br><span class="line"></span><br><span class="line">mysql&gt; select @@version;</span><br><span class="line">+-----------+</span><br><span class="line">| @@version |</span><br><span class="line">+-----------+</span><br><span class="line">| 5.6.25    |</span><br><span class="line">+-----------+</span><br><span class="line">1 row in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h3 id="3-2、准备数据"><a href="#3-2、准备数据" class="headerlink" title="3.2、准备数据"></a>3.2、准备数据</h3><p><strong>网址：<a href="https://dev.mysql.com/doc/sakila/en/sakila-installation.html" target="_blank" rel="noopener">https://dev.mysql.com/doc/sakila/en/sakila-installation.html</a></strong></p>
<p> 步骤：</p>
<p>1、通过命令行来连接数据库</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">shell&gt; mysql -u root -p</span><br></pre></td></tr></table></figure>
<p>2、创建表及语句执行</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SOURCE C:/temp/sakila-db/sakila-schema.sql;</span><br></pre></td></tr></table></figure>
<p>3、加载数据</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; SOURCE C:/temp/sakila-db/sakila-data.sql;</span><br></pre></td></tr></table></figure>
<p>4、使用数据库</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">USE sakila;</span><br></pre></td></tr></table></figure>
<p>5、检查创建的表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">SHOW TABLES;</span><br><span class="line"></span><br><span class="line">+----------------------------+</span><br><span class="line">| Tables_in_sakila           |</span><br><span class="line">+----------------------------+</span><br><span class="line">| actor                      |</span><br><span class="line">| actor_info                 |</span><br><span class="line">| address                    |</span><br><span class="line">| category                   |</span><br><span class="line">| city                       |</span><br><span class="line">| country                    |</span><br><span class="line">| customer                   |</span><br><span class="line">| customer_list              |</span><br><span class="line">| film                       |</span><br><span class="line">| film_actor                 |</span><br><span class="line">| film_category              |</span><br><span class="line">| film_list                  |</span><br><span class="line">| film_text                  |</span><br><span class="line">| inventory                  |</span><br><span class="line">| language                   |</span><br><span class="line">| nicer_but_slower_film_list |</span><br><span class="line">| payment                    |</span><br><span class="line">| rental                     |</span><br><span class="line">| sales_by_film_category     |</span><br><span class="line">| sales_by_store             |</span><br><span class="line">| staff                      |</span><br><span class="line">| staff_list                 |</span><br><span class="line">| store                      |</span><br><span class="line">+----------------------------+</span><br></pre></td></tr></table></figure>
<p>6、检验数据是否加载进去</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; select count(*) from film;</span><br><span class="line">+----------+</span><br><span class="line">| count(*) |</span><br><span class="line">+----------+</span><br><span class="line">|     1000 |</span><br><span class="line">+----------+</span><br><span class="line">1 row in set (0.00 sec)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">mysql&gt; select count(*) from payment ;</span><br><span class="line">+----------+</span><br><span class="line">| count(*) |</span><br><span class="line">+----------+</span><br><span class="line">|    16049 |</span><br><span class="line">+----------+</span><br><span class="line">1 row in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select count(*) from staff ;</span><br><span class="line">+----------+</span><br><span class="line">| count(*) |</span><br><span class="line">+----------+</span><br><span class="line">|        2 |</span><br><span class="line">+----------+</span><br><span class="line">1 row in set (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; select count(*) from store;</span><br><span class="line">+----------+</span><br><span class="line">| count(*) |</span><br><span class="line">+----------+</span><br><span class="line">|        2 |</span><br><span class="line">+----------+</span><br><span class="line">1 row in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<p>注：该表结构关系是用工具生成的。（powerDisigner）</p>
<h3 id="3-3、如何发现有问题的SQL"><a href="#3-3、如何发现有问题的SQL" class="headerlink" title="3.3、如何发现有问题的SQL"></a>3.3、如何发现有问题的SQL</h3><p>MySQL慢查日志的开启方式和存储格式</p>
<h4 id="3-3-1、检查慢查日志是否开启："><a href="#3-3-1、检查慢查日志是否开启：" class="headerlink" title="3.3.1、检查慢查日志是否开启："></a>3.3.1、检查慢查日志是否开启：</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">_query_log&apos;</span><br><span class="line"></span><br><span class="line">mysql&gt; show variables like &apos;slow_query_log&apos;;</span><br><span class="line">+----------------+-------+</span><br><span class="line">| Variable_name  | Value |</span><br><span class="line">+----------------+-------+</span><br><span class="line">| slow_query_log | OFF   |</span><br><span class="line">+----------------+-------+</span><br><span class="line">1 row in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h4 id="3-3-2、查看所有日志的变量信息"><a href="#3-3-2、查看所有日志的变量信息" class="headerlink" title="3.3.2、查看所有日志的变量信息"></a>3.3.2、查看所有日志的变量信息</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; show variables like &apos;%log%&apos;;</span><br><span class="line"></span><br><span class="line">+-----------------------------------------+------------------------------------+</span><br><span class="line"></span><br><span class="line">| Variable_name                           | Value                              |</span><br><span class="line"></span><br><span class="line">+-----------------------------------------+------------------------------------+</span><br><span class="line"></span><br><span class="line">| back_log                               |80                                 |</span><br><span class="line"></span><br><span class="line">| binlog_cache_size                       | 32768                              |</span><br><span class="line"></span><br><span class="line">| binlog_checksum                         | CRC32                              |</span><br><span class="line"></span><br><span class="line">| binlog_direct_non_transactional_updates |OFF                                |</span><br><span class="line"></span><br><span class="line">| binlog_error_action                     | IGNORE_ERROR                       |</span><br><span class="line"></span><br><span class="line">| binlog_format                           | STATEMENT                          |</span><br><span class="line"></span><br><span class="line">| binlog_gtid_simple_recovery             | OFF                                |</span><br><span class="line"></span><br><span class="line">| binlog_max_flush_queue_time             | 0                                  |</span><br><span class="line"></span><br><span class="line">| binlog_order_commits                    | ON                                 |</span><br><span class="line"></span><br><span class="line">| binlog_row_image                        | FULL                               |</span><br><span class="line"></span><br><span class="line">| binlog_rows_query_log_events            | OFF                                |</span><br><span class="line"></span><br><span class="line">| binlog_stmt_cache_size                  | 32768                              |</span><br><span class="line"></span><br><span class="line">| binlogging_impossible_mode              | IGNORE_ERROR                       |</span><br><span class="line"></span><br><span class="line">| expire_logs_days                        | 0                                  |</span><br><span class="line"></span><br><span class="line">| general_log                             | OFF                                |</span><br><span class="line"></span><br><span class="line">| general_log_file                        |/var/lib/mysql/mysql-host.log      |</span><br><span class="line"></span><br><span class="line">| innodb_api_enable_binlog                | OFF                                |</span><br><span class="line"></span><br><span class="line">| innodb_flush_log_at_timeout             | 1                                  |</span><br><span class="line"></span><br><span class="line">| innodb_flush_log_at_trx_commit          | 1                                  |</span><br><span class="line"></span><br><span class="line">| innodb_locks_unsafe_for_binlog          | OFF                                |</span><br><span class="line"></span><br><span class="line">| innodb_log_buffer_size                  | 8388608                            |</span><br><span class="line"></span><br><span class="line">| innodb_log_compressed_pages             | ON                                 |</span><br><span class="line"></span><br><span class="line">| innodb_log_file_size                    | 50331648                           |</span><br><span class="line"></span><br><span class="line">| innodb_log_files_in_group               | 2                                  |</span><br><span class="line"></span><br><span class="line">| innodb_log_group_home_dir               | ./                                 |</span><br><span class="line"></span><br><span class="line">| innodb_mirrored_log_groups              | 1                                  |</span><br><span class="line"></span><br><span class="line">| innodb_online_alter_log_max_size        | 134217728                          |</span><br><span class="line"></span><br><span class="line">| innodb_undo_logs                        | 128                                |</span><br><span class="line"></span><br><span class="line">| log_bin                                 | OFF                                |</span><br><span class="line"></span><br><span class="line">| log_bin_basename                        |                                    |</span><br><span class="line"></span><br><span class="line">| log_bin_index                           |                                    |</span><br><span class="line"></span><br><span class="line">| log_bin_trust_function_creators         | OFF                                |</span><br><span class="line"></span><br><span class="line">| log_bin_use_v1_row_events               | OFF                                |</span><br><span class="line"></span><br><span class="line">| log_error                               |/var/log/mysqld.log                |</span><br><span class="line"></span><br><span class="line">| log_output                              | FILE                               |</span><br><span class="line"></span><br><span class="line">| log_queries_not_using_indexes           | ON                                 |</span><br><span class="line"></span><br><span class="line">| log_slave_updates                       | OFF                                |</span><br><span class="line"></span><br><span class="line">| log_slow_admin_statements               | OFF                                |</span><br><span class="line"></span><br><span class="line">| log_slow_slave_statements               | OFF                                |</span><br><span class="line"></span><br><span class="line">|log_throttle_queries_not_using_indexes  |0                                  |</span><br><span class="line"></span><br><span class="line">| log_warnings                            | 1                                  |</span><br><span class="line"></span><br><span class="line">| max_binlog_cache_size                   | 18446744073709547520               |</span><br><span class="line"></span><br><span class="line">| max_binlog_size                         | 1073741824                         |</span><br><span class="line"></span><br><span class="line">| max_binlog_stmt_cache_size              | 18446744073709547520               |</span><br><span class="line"></span><br><span class="line">| max_relay_log_size                      | 0                                  |</span><br><span class="line"></span><br><span class="line">| relay_log                               |                                    |</span><br><span class="line"></span><br><span class="line">| relay_log_basename                      |                                    |</span><br><span class="line"></span><br><span class="line">| relay_log_index                         |                                    |</span><br><span class="line"></span><br><span class="line">| relay_log_info_file                     | relay-log.info                     |</span><br><span class="line"></span><br><span class="line">| relay_log_info_repository               | FILE                               |</span><br><span class="line"></span><br><span class="line">| relay_log_purge                         | ON                                 |</span><br><span class="line"></span><br><span class="line">| relay_log_recovery                      | OFF                                |</span><br><span class="line"></span><br><span class="line">| relay_log_space_limit                   | 0                                  |</span><br><span class="line"></span><br><span class="line">| simplified_binlog_gtid_recovery         | OFF                                |</span><br><span class="line"></span><br><span class="line">|slow_query_log                          |OFF                                |</span><br><span class="line"></span><br><span class="line">| slow_query_log_file                     |/var/lib/mysql/mysql-host-slow.log |</span><br><span class="line"></span><br><span class="line">| sql_log_bin                             | ON                                 |</span><br><span class="line"></span><br><span class="line">| sql_log_off                             | OFF                                |</span><br><span class="line"></span><br><span class="line">| sync_binlog                             | 0                                  |</span><br><span class="line"></span><br><span class="line">| sync_relay_log                          | 10000                              |</span><br><span class="line"></span><br><span class="line">| sync_relay_log_info                     | 10000                              |</span><br><span class="line"></span><br><span class="line">+-----------------------------------------+------------------------------------+</span><br></pre></td></tr></table></figure>
<p>61 rows in set (0.01 sec)</p>
<p>开启慢查日志：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show variables like &apos;%log%&apos;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">log_queries_not_using_indexes           | ON                            |</span><br><span class="line"></span><br><span class="line"> slow_query_log                          | OFF                           |</span><br><span class="line">| slow_query_log_file                     | /var/lib/mysql/mysql-slow.log |</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">//通过这个命令来设置开启慢日志</span><br><span class="line">mysql&gt; set global slow_query_log=on;</span><br><span class="line">Query OK, 0 rows affected (0.32 sec)</span><br></pre></td></tr></table></figure>
<p>验证慢查询日志是否开启：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># Time: 181026  0:39:29</span><br><span class="line"># User@Host: root[root] @ localhost []  Id:     3</span><br><span class="line"># Query_time: 0.000098  Lock_time: 0.000050 Rows_sent: 1  Rows_examined: 2</span><br><span class="line">SET timestamp=1540485569;</span><br><span class="line">select count(*) from staff;</span><br></pre></td></tr></table></figure>
<p>在mysql操作中，</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Show databases;</span><br><span class="line"></span><br><span class="line">Use sakila;</span><br><span class="line"></span><br><span class="line">select * from store;</span><br><span class="line"></span><br><span class="line">select * from staff;</span><br></pre></td></tr></table></figure>
<p>监听日志文件，看是否写入</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tail -f /var/lib/mysql/mysql-slow.log</span><br></pre></td></tr></table></figure>
<h4 id="3-3-3、MySQL慢查日志的存储格式"><a href="#3-3-3、MySQL慢查日志的存储格式" class="headerlink" title="3.3.3、MySQL慢查日志的存储格式"></a>3.3.3、MySQL慢查日志的存储格式</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">show variables like &apos;slow%&apos;;</span><br><span class="line"></span><br><span class="line">+---------------------+---------------------------------------------------------------------+</span><br><span class="line">| Variable_name       | Value                                                               |</span><br><span class="line">+---------------------+---------------------------------------------------------------------+</span><br><span class="line">| slow_launch_time    | 2                                                                   |</span><br><span class="line">| slow_query_log      | OFF                                                                 |</span><br><span class="line">| slow_query_log_file | C:\ProgramData\MySQL\MySQL Server 5.5\Data\DESKTOP-2LA2VDS-slow.log |</span><br><span class="line">+---------------------+---------------------------------------------------------------------+</span><br></pre></td></tr></table></figure>
<p>参数说明：</p>
<pre><code>1、# Time: 180526  1:06:54 -------à查询的执行时间

2、# User@Host: root[root] @ localhost []  Id:     4 -------à执行sql的主机信息

3、# Query_time: 0.000401 Lock_time: 0.000105 Rows_sent: 2 Rows_examined: 2-------àSQL的执行信息：

              Query_time：SQL的查询时间

              Lock_time：锁定时间

              Rows_sent：所发送的行数

              Rows_examined：锁扫描的行数

4、SET timestamp=1527268014; -------àSQL执行时间

5、select * from staff; -------àSQL的执行内容
</code></pre><h2 id="4、MySQL慢查日志分析工具（mysqldumpslow）"><a href="#4、MySQL慢查日志分析工具（mysqldumpslow）" class="headerlink" title="4、MySQL慢查日志分析工具（mysqldumpslow）"></a>4、MySQL慢查日志分析工具（mysqldumpslow）</h2><h3 id="1、介绍"><a href="#1、介绍" class="headerlink" title="1、介绍"></a>1、介绍</h3><p>如何进行查看慢查询日志，如果开启了慢查询日志，就会生成很多的数据，然后我们就可以通过对日志的分析，生成分析报表，然后通过报表进行优化。</p>
<h3 id="2、用法"><a href="#2、用法" class="headerlink" title="2、用法"></a>2、用法</h3><p>接下来我们查看一下这个工具的用法</p>
<p>注意：在mysql数据库所在的服务器上，而不是在mysql&gt;命令行中</p>
<p>该工具如何使用：<strong>mysqldumpslow -h</strong></p>
<p><strong>查看verbose信息</strong></p>
<p><strong>Mysqldumpslow -v</strong></p>
<p>查看慢查询日志的前10个，mysqldumpslow 分析的结果如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# mysqldumpslow -t 10 /var/lib/mysql/mysql-slow.log</span><br><span class="line"></span><br><span class="line">Reading mysql slow query log from /var/lib/mysql/mysql-slow.log</span><br><span class="line">Count: 1  Time=0.01s (0s)  Lock=0.00s (0s)  Rows=1000.0 (1000), root[root]@localhost</span><br><span class="line">  select * from film</span><br><span class="line"></span><br><span class="line">Count: 1  Time=0.00s (0s)  Lock=0.00s (0s)  Rows=200.0 (200), root[root]@localhost</span><br><span class="line">  select * from actor</span><br><span class="line"></span><br><span class="line">Count: 2  Time=0.00s (0s)  Lock=0.00s (0s)  Rows=1.0 (2), root[root]@localhost</span><br><span class="line">  select count(*) from film</span><br><span class="line"></span><br><span class="line">Count: 2  Time=0.00s (0s)  Lock=0.00s (0s)  Rows=1.0 (2), root[root]@localhost</span><br><span class="line">  select count(*) from staff</span><br><span class="line"></span><br><span class="line">Died at /usr/bin/mysqldumpslow line 161, &lt;&gt; chunk 6.</span><br></pre></td></tr></table></figure>
<p>如上图两条就是分析的结果，每条结果都显示是执行时间，锁定时间，发送的行数，扫描的行数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql mysql]# tail -f /var/lib/mysql/mysql-slow.log</span><br><span class="line"># Time: 181026  0:41:46</span><br><span class="line"># User@Host: root[root] @ localhost []  Id:     3</span><br><span class="line"># Query_time: 0.000121  Lock_time: 0.000059 Rows_sent: 1  Rows_examined: 2</span><br><span class="line">SET timestamp=1540485706;</span><br><span class="line">select count(*) from staff;</span><br><span class="line"># Time: 181026  0:42:12</span><br><span class="line"># User@Host: root[root] @ localhost []  Id:     3</span><br><span class="line"># Query_time: 0.000634  Lock_time: 0.000069 Rows_sent: 200  Rows_examined: 200</span><br><span class="line">SET timestamp=1540485732;</span><br><span class="line">select * from actor;</span><br><span class="line"># Time: 181026  1:05:41</span><br><span class="line"># User@Host: root[root] @ localhost []  Id:     3</span><br><span class="line"># Query_time: 0.008336  Lock_time: 0.000101 Rows_sent: 1000  Rows_examined: 1000</span><br><span class="line">SET timestamp=1540487141;</span><br><span class="line">select * from film;</span><br></pre></td></tr></table></figure>
<p>这个工具是最常用的工具，通过安装mysql进行附带安装，但是该工具统计的结果比较少，对我们的优化锁表现的数据还是比较少。</p>
<h2 id="5、MySQL慢查日志分析工具-pt-query-digest"><a href="#5、MySQL慢查日志分析工具-pt-query-digest" class="headerlink" title="5、MySQL慢查日志分析工具(pt-query-digest)"></a>5、MySQL慢查日志分析工具(pt-query-digest)</h2><h3 id="1、介绍及作用"><a href="#1、介绍及作用" class="headerlink" title="1、介绍及作用"></a>1、介绍及作用</h3><pre><code>作为一名优秀的mysql dba也需要有掌握几个好用的mysql管理工具，所以我也一直在整理和查找一些能够便于管理mysql的利器。以后的一段时间内，将会花一大部分的精力去搜索这些工具。
</code></pre><p>性 能的管理一直都是摆在第一位的，dba的很多工作管理层都看不到也没有办法衡量价值，但是如果一个系统慢的跟蜗牛一样，dba通过监控调优把系统从崩溃边缘重新拉回到高铁时代。这种价值和触动应该是巨大的。（很多企业的领导认为系统跑不动了就需要换更快的CPU、更大的内存、更快的存储，而且这还不是少数，所以DBA的价值也一直体现不出来，薪水自然也就不会很高）</p>
<p>mysql 的日志是跟踪mysql性能瓶颈的最快和最直接的方式了，系统性能出现瓶颈的时候，首先要打开慢查询日志，进行跟踪；这段时间关于慢查询日志的管理和查看已经整理过两篇文章了，不经意间又发现了一个查看慢查询日志的工具：mk-query-digest，这个工具网上号称mysql dba必须掌握的十大工具之首。</p>
<h2 id="2、安装pt-query-digest工具"><a href="#2、安装pt-query-digest工具" class="headerlink" title="2、安装pt-query-digest工具"></a>2、安装pt-query-digest工具</h2><h3 id="1-1、快速安装（注：必须先要安装wget）"><a href="#1-1、快速安装（注：必须先要安装wget）" class="headerlink" title="1.1、快速安装（注：必须先要安装wget）"></a>1.1、快速安装（注：必须先要安装wget）</h3><h3 id="1-2、检查是否安装完成："><a href="#1-2、检查是否安装完成：" class="headerlink" title="1.2、检查是否安装完成："></a>1.2、检查是否安装完成：</h3><pre><code>命令行中输入：pt-summary

      显示如下图所示：说明安装成功！输入【[root@node03 mysql]# pt-query-digest --help】
</code></pre><h3 id="1-3、工具使用简介："><a href="#1-3、工具使用简介：" class="headerlink" title="1.3、工具使用简介："></a>1.3、工具使用简介：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-summary --help</span><br><span class="line">Usage: pt-summary</span><br><span class="line"></span><br><span class="line">For more information, &apos;man pt-summary&apos; or &apos;perldoc /usr/bin/pt-summary&apos;.</span><br><span class="line"></span><br><span class="line">Command line options:</span><br><span class="line"></span><br><span class="line">  --config          Read this comma-separated list of config files.</span><br><span class="line">  --help            Print help and exit.</span><br><span class="line">  --read-samples    Create a report from the files in this directory.</span><br><span class="line">  --save-samples    Save the collected data in this directory.</span><br><span class="line">  --sleep           How long to sleep when gathering samples from vmstat.</span><br><span class="line">  --summarize-mounts</span><br><span class="line">                    Report on mounted filesystems and disk usage.</span><br><span class="line">  --summarize-network</span><br><span class="line">                    Report on network controllers and configuration.</span><br><span class="line">  --summarize-processes</span><br><span class="line">                    Report on top processes and C&lt;vmstat&gt; output.</span><br><span class="line">  --version         Print tool&apos;s version and exit.</span><br><span class="line"></span><br><span class="line">Options and values after processing arguments:</span><br><span class="line"></span><br><span class="line">  --config                         (No value)</span><br><span class="line">  --help                           TRUE</span><br><span class="line">  --read-samples                   (No value)</span><br><span class="line">  --save-samples                   (No value)</span><br><span class="line">  --sleep                          5</span><br><span class="line">  --summarize-mounts               TRUE</span><br><span class="line">  --summarize-network              TRUE</span><br><span class="line">  --summarize-processes            TRUE</span><br><span class="line">  --version                        FALSE</span><br><span class="line">[root@mysql ~]# pt-summary --version</span><br><span class="line">pt-summary 2.2.16</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="1、查看服务器信息"><a href="#1、查看服务器信息" class="headerlink" title="1、查看服务器信息"></a>1、查看服务器信息</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# man pt-summary</span><br><span class="line">PT-SUMMARY(1p)        User Contributed Perl Documentation       PT-SUMMARY(1p)</span><br><span class="line"></span><br><span class="line">NAME</span><br><span class="line">       pt-summary - Summarize system information nicely.</span><br><span class="line"></span><br><span class="line">SYNOPSIS</span><br><span class="line">       Usage: pt-summary</span><br><span class="line"></span><br><span class="line">       pt-summary conveniently summarizes the status and configuration of a server.  It is not a tuning tool</span><br><span class="line">       or diagnosis tool.  It produces a report that is easy to diff and can be pasted into emails without</span><br><span class="line">       losing the formatting.  This tool works well on many types of Unix systems.</span><br><span class="line"></span><br><span class="line">       Download and run:</span><br><span class="line"></span><br><span class="line">          wget http://percona.com/get/pt-summary</span><br><span class="line">          bash ./pt-summary</span><br><span class="line"></span><br><span class="line">RISKS</span><br><span class="line">       Percona Toolkit is mature, proven in the real world, and well tested, but all database tools can pose</span><br><span class="line">       a risk to the system and the database server.  Before using this tool, please:</span><br><span class="line"></span><br><span class="line">       Â·   Read the toolâ€™s documentation</span><br><span class="line"></span><br><span class="line">       Â·   Review the toolâ€™s known &quot;BUGS&quot;</span><br><span class="line"></span><br><span class="line">       Â·   Test the tool on a non-production server</span><br><span class="line"></span><br><span class="line">       Â·   Backup your production server and verify the backups</span><br><span class="line"></span><br><span class="line">DESCRIPTION</span><br><span class="line">       pt-summary runs a large variety of commands to inspect system status and configuration, saves the</span><br><span class="line">       output into files in a temporary directory, and then runs Unix commands on these results to format</span><br><span class="line">       them nicely.  It works best when executed as a privileged user, but will also work without</span><br><span class="line">       privileges, although some output might not be possible to generate without root.</span><br><span class="line"></span><br><span class="line">OUTPUT</span><br><span class="line">       Many of the outputs from this tool are deliberately rounded to show their magnitude but not the exact</span><br><span class="line">       detail. This is called fuzzy-rounding. The idea is that it doesnâ€™t matter whether a particular</span><br><span class="line">       counter is 918 or 921; such a small variation is insignificant, and only makes the output hard to</span><br><span class="line">       compare to other servers. Fuzzy-rounding rounds in larger increments as the input grows. It begins by</span><br><span class="line">       rounding to the nearest 5, then the nearest 10, nearest 25, and then repeats by a factor of 10 larger</span><br><span class="line">       (50, 100, 250), and so on, as the input grows.</span><br><span class="line"></span><br><span class="line">       The following is a simple report generated from a CentOS virtual machine, broken into sections with</span><br><span class="line">       commentary following each section. Some long lines are reformatted for clarity when reading this</span><br><span class="line">       documentation as a manual page in a terminal.</span><br><span class="line"></span><br><span class="line">        # Percona Toolkit System Summary Report ######################</span><br><span class="line">                Date | 2012-03-30 00:58:07 UTC (local TZ: EDT -0400)</span><br><span class="line">            Hostname | localhost.localdomain</span><br><span class="line">              Uptime | 20:58:06 up 1 day, 20 min, 1 user,</span><br><span class="line">                       load average: 0.14, 0.18, 0.18</span><br><span class="line">              System | innotek GmbH; VirtualBox; v1.2 ()</span><br><span class="line">         Service Tag | 0</span><br><span class="line">            Platform | Linux</span><br><span class="line">             Release | CentOS release 5.5 (Final)</span><br><span class="line">              Kernel | 2.6.18-194.el5</span><br><span class="line">        Architecture | CPU = 32-bit, OS = 32-bit</span><br><span class="line">           Threading | NPTL 2.5</span><br><span class="line">            Compiler | GNU CC version 4.1.2 20080704 (Red Hat 4.1.2-48).</span><br><span class="line">             SELinux | Enforcing</span><br><span class="line">         Virtualized | VirtualBox</span><br><span class="line"></span><br><span class="line">       This section shows the current date and time, and a synopsis of the server and operating system.</span><br><span class="line"></span><br><span class="line">        # Processor ##################################################</span><br><span class="line">          Processors | physical = 1, cores = 0, virtual = 1, hyperthreading = no</span><br><span class="line">              Speeds | 1x2510.626</span><br><span class="line">              Models | 1xIntel(R) Core(TM) i5-2400S CPU @ 2.50GHz</span><br><span class="line">              Caches | 1x6144 KB</span><br><span class="line"></span><br><span class="line">       This section is derived from /proc/cpuinfo.</span><br><span class="line"></span><br><span class="line">        # Memory #####################################################</span><br><span class="line">               Total | 503.2M</span><br><span class="line">                Free | 29.0M</span><br><span class="line">                Used | physical = 474.2M, swap allocated = 1.0M,</span><br><span class="line">                       swap used = 16.0k, virtual = 474.3M</span><br><span class="line">             Buffers | 33.9M</span><br><span class="line">              Caches | 262.6M</span><br><span class="line">               Dirty | 396 kB</span><br><span class="line">             UsedRSS | 201.9M</span><br><span class="line">          Swappiness | 60</span><br><span class="line">         DirtyPolicy | 40, 10</span><br><span class="line">         Locator  Size  Speed    Form Factor  Type    Type Detail</span><br><span class="line">         =======  ====  =====    ===========  ====    ===========</span><br><span class="line"></span><br><span class="line">       Information about memory is gathered from &quot;free&quot;. The Used statistic is the total of the rss sizes</span><br><span class="line">       displayed by &quot;ps&quot;. The Dirty statistic for the cached value comes from /proc/meminfo. On Linux, the</span><br><span class="line">       swappiness settings are gathered from &quot;sysctl&quot;. The final portion of this section is a table of the</span><br><span class="line">       DIMMs, which comes from &quot;dmidecode&quot;. In this example there is no output.</span><br><span class="line"></span><br><span class="line">        # Mounted Filesystems ########################################</span><br><span class="line">          Filesystem                       Size Used Type  Opts Mountpoint</span><br><span class="line">          /dev/mapper/VolGroup00-LogVol00   15G  17% ext3  rw   /</span><br><span class="line">          /dev/sda1                         99M  13% ext3  rw   /boot</span><br><span class="line">          tmpfs                            252M   0% tmpfs rw   /dev/shm</span><br><span class="line"></span><br><span class="line">       The mounted filesystem section is a combination of information from &quot;mount&quot; and &quot;df&quot;. This section is</span><br><span class="line">       skipped if you disable &quot;--summarize-mounts&quot;.</span><br><span class="line"></span><br><span class="line">        # Disk Schedulers And Queue Size #############################</span><br><span class="line">                dm-0 | UNREADABLE</span><br><span class="line">                dm-1 | UNREADABLE</span><br><span class="line">                 hdc | [cfq] 128</span><br><span class="line">                 md0 | UNREADABLE</span><br><span class="line">                 sda | [cfq] 128</span><br><span class="line"></span><br><span class="line">       The disk scheduler information is extracted from the /sys filesystem in Linux.</span><br><span class="line"></span><br><span class="line">        # Disk Partioning ############################################</span><br><span class="line">        Device       Type      Start        End               Size</span><br><span class="line">        ============ ==== ========== ========== ==================</span><br><span class="line">        /dev/sda     Disk                              17179869184</span><br><span class="line">        /dev/sda1    Part          1         13           98703360</span><br><span class="line">        /dev/sda2    Part         14       2088        17059230720</span><br><span class="line"></span><br><span class="line">       Information about disk partitioning comes from &quot;fdisk -l&quot;.</span><br><span class="line"></span><br><span class="line">        # Kernel Inode State #########################################</span><br><span class="line">        dentry-state | 10697 8559  45 0  0  0</span><br><span class="line">             file-nr | 960   0  50539</span><br><span class="line">            inode-nr | 14059 8139</span><br><span class="line"></span><br><span class="line">       These lines are from the files of the same name in the /proc/sys/fs directory on Linux. Read the</span><br><span class="line">       &quot;proc&quot; man page to learn about the meaning of these files on your system.</span><br><span class="line"></span><br><span class="line">        # LVM Volumes ################################################</span><br><span class="line">        LV       VG         Attr   LSize   Origin Snap% Move Log Copy% Convert</span><br><span class="line">        LogVol00 VolGroup00 -wi-ao 269.00G</span><br><span class="line">        LogVol01 VolGroup00 -wi-ao   9.75G</span><br><span class="line"></span><br><span class="line">       This section shows the output of &quot;lvs&quot;.</span><br><span class="line"></span><br><span class="line">        # RAID Controller ############################################</span><br><span class="line">          Controller | No RAID controller detected</span><br><span class="line"></span><br><span class="line">       The tool can detect a variety of RAID controllers by examining &quot;lspci&quot; and &quot;dmesg&quot; information. If</span><br><span class="line">       the controller software is installed on the system, in many cases it is able to execute status</span><br><span class="line">       commands and show a summary of the RAID controllerâ€™s status and configuration. If your system is not</span><br><span class="line">       supported, please file a bug report.</span><br><span class="line"></span><br><span class="line">        # Network Config #############################################</span><br><span class="line">          Controller | Intel Corporation 82540EM Gigabit Ethernet Controller</span><br><span class="line">         FIN Timeout | 60</span><br><span class="line">          Port Range | 61000</span><br><span class="line"></span><br><span class="line">       The network controllers attached to the system are detected from &quot;lspci&quot;. The TCP/IP protocol</span><br><span class="line">       configuration parameters are extracted from &quot;sysctl&quot;. You can skip this section by disabling the</span><br><span class="line">       &quot;--summarize-network&quot; option.</span><br><span class="line"></span><br><span class="line">        # Interface Statistics #######################################</span><br><span class="line">        interface rx_bytes rx_packets rx_errors tx_bytes tx_packets tx_errors</span><br><span class="line">        ========= ======== ========== ========= ======== ========== =========</span><br><span class="line">        lo        60000000      12500         0 60000000      12500         0</span><br><span class="line">        eth0      15000000      80000         0  1500000      10000         0</span><br><span class="line">        sit0             0          0         0        0          0         0</span><br><span class="line"></span><br><span class="line">       Interface statistics are gathered from &quot;ip -s link&quot; and are fuzzy-rounded. The columns are received</span><br><span class="line">       and transmitted bytes, packets, and errors.  You can skip this section by disabling the</span><br><span class="line">       &quot;--summarize-network&quot; option.</span><br><span class="line"></span><br><span class="line">        # Network Connections ########################################</span><br><span class="line">          Connections from remote IP addresses</span><br><span class="line">            127.0.0.1           2</span><br><span class="line">          Connections to local IP addresses</span><br><span class="line">            127.0.0.1           2</span><br><span class="line">          Connections to top 10 local ports</span><br><span class="line">            38346               1</span><br><span class="line">            60875               1</span><br><span class="line">          States of connections</span><br><span class="line">            ESTABLISHED         5</span><br><span class="line">            LISTEN              8</span><br><span class="line"></span><br><span class="line">       This section shows a summary of network connections, retrieved from &quot;netstat&quot; and &quot;fuzzy-rounded&quot; to</span><br><span class="line">       make them easier to compare when the numbers grow large.  There are two sub-sections showing how many</span><br><span class="line">       connections there are per origin and destination IP address, and a sub-section showing the count of</span><br><span class="line">       ports in use.  The section ends with the count of the network connectionsâ€™ states.  You can skip this</span><br><span class="line">       section by disabling the &quot;--summarize-network&quot; option.</span><br><span class="line"></span><br><span class="line">        # Top Processes ##############################################</span><br><span class="line">          PID USER  PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND</span><br><span class="line">            1 root  15   0  2072  628  540 S  0.0  0.1   0:02.55 init</span><br><span class="line">            2 root  RT  -5     0    0    0 S  0.0  0.0   0:00.00 migration/0</span><br><span class="line">            3 root  34  19     0    0    0 S  0.0  0.0   0:00.03 ksoftirqd/0</span><br><span class="line">            4 root  RT  -5     0    0    0 S  0.0  0.0   0:00.00 watchdog/0</span><br><span class="line">            5 root  10  -5     0    0    0 S  0.0  0.0   0:00.97 events/0</span><br><span class="line">            6 root  10  -5     0    0    0 S  0.0  0.0   0:00.00 khelper</span><br><span class="line">            7 root  10  -5     0    0    0 S  0.0  0.0   0:00.00 kthread</span><br><span class="line">           10 root  10  -5     0    0    0 S  0.0  0.0   0:00.13 kblockd/0</span><br><span class="line">           11 root  20  -5     0    0    0 S  0.0  0.0   0:00.00 kacpid</span><br><span class="line">        # Notable Processes ##########################################</span><br><span class="line">          PID    OOM    COMMAND</span><br><span class="line">         2028    +0    sshd</span><br><span class="line"></span><br><span class="line">       This section shows the first few lines of &quot;top&quot; so that you can see what processes are actively using</span><br><span class="line">       CPU time.  The notable processes include the SSH daemon and any process whose out-of-memory-killer</span><br><span class="line">       priority is set to 17. You can skip this section by disabling the &quot;--summarize-processes&quot; option.</span><br><span class="line"></span><br><span class="line">        # Simplified and fuzzy rounded vmstat (wait please) ##########</span><br><span class="line">          procs  ---swap-- -----io---- ---system---- --------cpu--------</span><br><span class="line">           r  b    si   so    bi    bo     ir     cs  us  sy  il  wa  st</span><br><span class="line">           2  0     0    0     3    15     30    125   0   0  99   0   0</span><br><span class="line">           0  0     0    0     0     0   1250    800   6  10  84   0   0</span><br><span class="line">           0  0     0    0     0     0   1000    125   0   0 100   0   0</span><br><span class="line">           0  0     0    0     0     0   1000    125   0   0 100   0   0</span><br><span class="line">           0  0     0    0     0   450   1000    125   0   1  88  11   0</span><br><span class="line">        # The End ####################################################</span><br><span class="line"></span><br><span class="line">       This section is a trimmed-down sample of &quot;vmstat 1 5&quot;, so you can see the general status of the</span><br><span class="line">       system at present. The values in the table are fuzzy-rounded, except for the CPU columns.  You can</span><br><span class="line">       skip this section by disabling the &quot;--summarize-processes&quot; option.</span><br><span class="line"></span><br><span class="line">OPTIONS</span><br><span class="line">       --config</span><br><span class="line">           type: string</span><br><span class="line"></span><br><span class="line">           Read this comma-separated list of config files.  If specified, this must be the first option on</span><br><span class="line">           the command line.</span><br><span class="line"></span><br><span class="line">       --help</span><br><span class="line">           Print help and exit.</span><br><span class="line"></span><br><span class="line">       --read-samples</span><br><span class="line">           type: string</span><br><span class="line"></span><br><span class="line">           Create a report from the files in this directory.</span><br><span class="line"></span><br><span class="line">       --save-samples</span><br><span class="line">           type: string</span><br><span class="line"></span><br><span class="line">           Save the collected data in this directory.</span><br><span class="line"></span><br><span class="line">       --sleep</span><br><span class="line">           type: int; default: 5</span><br><span class="line"></span><br><span class="line">           How long to sleep when gathering samples from vmstat.</span><br><span class="line"></span><br><span class="line">       --summarize-mounts</span><br><span class="line">           default: yes; negatable: yes</span><br><span class="line"></span><br><span class="line">           Report on mounted filesystems and disk usage.</span><br><span class="line"></span><br><span class="line">       --summarize-network</span><br><span class="line">           default: yes; negatable: yes</span><br><span class="line"></span><br><span class="line">           Report on network controllers and configuration.</span><br><span class="line"></span><br><span class="line">       --summarize-processes</span><br><span class="line">           default: yes; negatable: yes</span><br><span class="line"></span><br><span class="line">           Report on top processes and &quot;vmstat&quot; output.</span><br><span class="line"></span><br><span class="line">       --version</span><br><span class="line">           Print toolâ€™s version and exit.</span><br><span class="line"></span><br><span class="line">ENVIRONMENT</span><br><span class="line">       This tool does not use any environment variables.</span><br><span class="line"></span><br><span class="line">SYSTEM REQUIREMENTS</span><br><span class="line">       This tool requires the Bourne shell (/bin/sh).</span><br><span class="line"></span><br><span class="line">BUGS</span><br><span class="line">       For a list of known bugs, see http://www.percona.com/bugs/pt-summary &lt;http://www.percona.com/bugs/pt-</span><br><span class="line">       summary&gt;.</span><br><span class="line"></span><br><span class="line">       Please report bugs at https://bugs.launchpad.net/percona-toolkit &lt;https://bugs.launchpad.net/percona-</span><br><span class="line">       toolkit&gt;.  Include the following information in your bug report:</span><br><span class="line"></span><br><span class="line">       Â·   Complete command-line used to run the tool</span><br><span class="line"></span><br><span class="line">       Â·   Tool &quot;--version&quot;</span><br><span class="line"></span><br><span class="line">       Â·   MySQL version of all servers involved</span><br><span class="line"></span><br><span class="line">       Â·   Output from the tool including STDERR</span><br><span class="line"></span><br><span class="line">       Â·   Input files (log/dump/config files, etc.)</span><br><span class="line"></span><br><span class="line">       If possible, include debugging output by running the tool with &quot;PTDEBUG&quot;; see &quot;ENVIRONMENT&quot;.</span><br><span class="line"></span><br><span class="line">DOWNLOADING</span><br><span class="line">       Visit http://www.percona.com/software/percona-toolkit/ &lt;http://www.percona.com/software/percona-</span><br><span class="line">       toolkit/&gt; to download the latest release of Percona Toolkit.  Or, get the latest release from the</span><br><span class="line">       command line:</span><br><span class="line"></span><br><span class="line">          wget percona.com/get/percona-toolkit.tar.gz</span><br><span class="line"></span><br><span class="line">          wget percona.com/get/percona-toolkit.rpm</span><br><span class="line"></span><br><span class="line">          wget percona.com/get/percona-toolkit.deb</span><br><span class="line"></span><br><span class="line">       You can also get individual tools from the latest release:</span><br><span class="line"></span><br><span class="line">          wget percona.com/get/TOOL</span><br><span class="line"></span><br><span class="line">       Replace &quot;TOOL&quot; with the name of any tool.</span><br><span class="line"></span><br><span class="line">AUTHORS</span><br><span class="line">       Baron Schwartz, Kevin van Zonneveld, and Brian Fraser</span><br><span class="line"></span><br><span class="line">ABOUT PERCONA TOOLKIT</span><br><span class="line">       This tool is part of Percona Toolkit, a collection of advanced command-line tools for MySQL developed</span><br><span class="line">       by Percona.  Percona Toolkit was forked from two projects in June, 2011: Maatkit and Aspersa.  Those</span><br><span class="line">       projects were created by Baron Schwartz and primarily developed by him and Daniel Nichter.  Visit</span><br><span class="line">       &lt;http://www.percona.com/software/&gt; to learn about other free, open-source software from Percona.</span><br><span class="line"></span><br><span class="line">COPYRIGHT, LICENSE, AND WARRANTY</span><br><span class="line">       This program is copyright 2011-2015 Percona LLC and/or its affiliates, 2010-2011 Baron Schwartz.</span><br><span class="line"></span><br><span class="line">       THIS PROGRAM IS PROVIDED &quot;AS IS&quot; AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT</span><br><span class="line">       LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.</span><br><span class="line"></span><br><span class="line">       This program is free software; you can redistribute it and/or modify it under the terms of the GNU</span><br><span class="line">       General Public License as published by the Free Software Foundation, version 2; OR the Perl Artistic</span><br><span class="line">       License.  On UNIX and similar systems, you can issue â€˜man perlgplâ€™ or â€˜man perlartisticâ€™ to read</span><br><span class="line">       these licenses.</span><br><span class="line"></span><br><span class="line">       You should have received a copy of the GNU General Public License along with this program; if not,</span><br><span class="line">       write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.</span><br><span class="line"></span><br><span class="line">VERSION</span><br><span class="line">       pt-summary 2.2.16</span><br><span class="line"></span><br><span class="line">perl v5.14.2                      2015-11-06                    PT-SUMMARY(1p)</span><br></pre></td></tr></table></figure>
<h4 id="2、查看磁盘开销使用信息"><a href="#2、查看磁盘开销使用信息" class="headerlink" title="2、查看磁盘开销使用信息"></a>2、查看磁盘开销使用信息</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-diskstats</span><br><span class="line">  #ts device    rd_s rd_avkb rd_mb_s rd_mrg rd_cnc   rd_rt    wr_s wr_avkb wr_mb_s wr_mrg wr_cnc   wr_rt busy in_prg    io_s  qtime stime</span><br><span class="line">  1.0 sda        0.0     0.0     0.0     0%    0.0     0.0     5.0     4.0     0.0     0%    0.0     4.8   0%      0     5.0    3.8   1.0</span><br><span class="line">  1.0 sda2       0.0     0.0     0.0     0%    0.0     0.0     5.0     4.0     0.0     0%    0.0     4.8   0%      0     5.0    3.8   1.0</span><br><span class="line">  1.0 dm-0       0.0     0.0     0.0     0%    0.0     0.0     5.0     4.0     0.0     0%    0.0     4.8   0%      0     5.0    3.8   1.0</span><br><span class="line"></span><br><span class="line">  1.0 sda        0.0     0.0     0.0     0%    0.0     0.0     0.0     0.0     0.0     0%    0.0     0.0   0%      0     0.0    0.0   0.0</span><br><span class="line">  1.0 sda2       0.0     0.0     0.0     0%    0.0     0.0     0.0     0.0     0.0     0%    0.0     0.0   0%      0     0.0    0.0   0.0</span><br><span class="line">  1.0 dm-0       0.0     0.0     0.0     0%    0.0     0.0     0.0     0.0     0.0     0%    0.0     0.0   0%      0     0.0    0.0   0.0</span><br><span class="line"></span><br><span class="line">  1.0 sda        0.0     0.0     0.0     0%    0.0     0.0     0.0     0.0     0.0     0%    0.0     0.0   0%      0     0.0    0.0   0.0</span><br><span class="line">  1.0 sda2       0.0     0.0     0.0     0%    0.0     0.0     0.0     0.0     0.0     0%    0.0     0.0   0%      0     0.0    0.0   0.0</span><br><span class="line">  1.0 dm-0       0.0     0.0     0.0     0%    0.0     0.0     0.0     0.0     0.0     0%    0.0     0.0   0%      0     0.0    0.0   0.0</span><br></pre></td></tr></table></figure>
<h4 id="3、查看mysql数据库信息"><a href="#3、查看mysql数据库信息" class="headerlink" title="3、查看mysql数据库信息"></a>3、查看mysql数据库信息</h4><p><img src="file:///C:/Users/Deborah/AppData/Local/Temp/msohtmlclip1/01/clip_image018.png" alt=""></p>
<h4 id="4、分析慢查询日志"><a href="#4、分析慢查询日志" class="headerlink" title="4、分析慢查询日志"></a>4、分析慢查询日志</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-query-digest /var/lib/mysql/mysql-slow.log </span><br><span class="line"></span><br><span class="line"># 410ms user time, 110ms system time, 24.40M rss, 204.76M vsz</span><br><span class="line"># Current date: Fri Oct 26 02:02:37 2018</span><br><span class="line"># Hostname: mysql</span><br><span class="line"># Files: /var/lib/mysql/mysql-slow.log</span><br><span class="line"># Overall: 8 total, 6 unique, 0.00 QPS, 0.00x concurrency ________________</span><br><span class="line"># Time range: 2018-10-26 00:36:02 to 01:50:11</span><br><span class="line"># Attribute          total     min     max     avg     95%  stddev  median</span><br><span class="line"># ============     ======= ======= ======= ======= ======= ======= =======</span><br><span class="line"># Exec time           27ms    98us    15ms     3ms    15ms     5ms     1ms</span><br><span class="line"># Lock time            2ms    50us     2ms   293us     2ms   471us   105us</span><br><span class="line"># Rows sent          1.18k       1    1000  150.75  964.41  315.86    0.99</span><br><span class="line"># Rows examine       3.14k       2    1000  401.88  964.41  450.80  578.59</span><br><span class="line"># Query size           279      18      92   34.88   88.31   22.24   24.84</span><br><span class="line"></span><br><span class="line"># Profile</span><br><span class="line"># Rank Query ID           Response time Calls R/Call V/M   Item</span><br><span class="line"># ==== ================== ============= ===== ====== ===== ===============</span><br><span class="line">#    1 0x3A23B0CB7839AF05  0.0153 55.9%     1 0.0153  0.00 SELECT INFORMATION_SCHEMA.TRIGGERS</span><br><span class="line">#    2 0x687D590364E29465  0.0083 30.5%     1 0.0083  0.00 SELECT film</span><br><span class="line">#    3 0x9134F278CE0AB549  0.0017  6.2%     1 0.0017  0.00 SELECT mysql.user</span><br><span class="line">#    4 0xEBA2FBA69B1FF476  0.0012  4.2%     2 0.0006  0.00 SELECT film</span><br><span class="line"># MISC 0xMISC              0.0009  3.1%     3 0.0003   0.0 &lt;2 ITEMS&gt;</span><br><span class="line"></span><br><span class="line"># Query 1: 0 QPS, 0x concurrency, ID 0x3A23B0CB7839AF05 at byte 1678 _____</span><br><span class="line"># This item is included in the report because it matches --limit.</span><br><span class="line"># Scores: V/M = 0.00</span><br><span class="line"># Time range: all events occurred at 2018-10-26 01:50:11</span><br><span class="line"># Attribute    pct   total     min     max     avg     95%  stddev  median</span><br><span class="line"># ============ === ======= ======= ======= ======= ======= ======= =======</span><br><span class="line"># Count         12       1</span><br><span class="line"># Exec time     55    15ms    15ms    15ms    15ms    15ms       0    15ms</span><br><span class="line"># Lock time     16   387us   387us   387us   387us   387us       0   387us</span><br><span class="line"># Rows sent      0       1       1       1       1       1       0       1</span><br><span class="line"># Rows examine   0       6       6       6       6       6       0       6</span><br><span class="line"># Query size    17      48      48      48      48      48       0      48</span><br><span class="line"># String:</span><br><span class="line"># Databases    sakila</span><br><span class="line"># Hosts        localhost</span><br><span class="line"># Users        root</span><br><span class="line"># Query_time distribution</span><br><span class="line">#   1us</span><br><span class="line">#  10us</span><br><span class="line"># 100us</span><br><span class="line">#   1ms</span><br><span class="line">#  10ms  ################################################################</span><br><span class="line"># 100ms</span><br><span class="line">#    1s</span><br><span class="line">#  10s+</span><br><span class="line"># Tables</span><br><span class="line">#    SHOW TABLE STATUS FROM `INFORMATION_SCHEMA` LIKE &apos;TRIGGERS&apos;\G</span><br><span class="line">#    SHOW CREATE TABLE `INFORMATION_SCHEMA`.`TRIGGERS`\G</span><br><span class="line"># EXPLAIN /*!50100 PARTITIONS*/</span><br><span class="line">SELECT COUNT(*) FROM INFORMATION_SCHEMA.TRIGGERS\G</span><br><span class="line"></span><br><span class="line"># Query 2: 0 QPS, 0x concurrency, ID 0x687D590364E29465 at byte 1208 _____</span><br><span class="line"># This item is included in the report because it matches --limit.</span><br><span class="line"># Scores: V/M = 0.00</span><br><span class="line"># Time range: all events occurred at 2018-10-26 01:05:41</span><br><span class="line"># Attribute    pct   total     min     max     avg     95%  stddev  median</span><br><span class="line"># ============ === ======= ======= ======= ======= ======= ======= =======</span><br><span class="line"># Count         12       1</span><br><span class="line"># Exec time     30     8ms     8ms     8ms     8ms     8ms       0     8ms</span><br><span class="line"># Lock time      4   101us   101us   101us   101us   101us       0   101us</span><br><span class="line"># Rows sent     82    1000    1000    1000    1000    1000       0    1000</span><br><span class="line"># Rows examine  31    1000    1000    1000    1000    1000       0    1000</span><br><span class="line"># Query size     6      18      18      18      18      18       0      18</span><br><span class="line"># String:</span><br><span class="line"># Databases    sakila</span><br><span class="line"># Hosts        localhost</span><br><span class="line"># Users        root</span><br><span class="line"># Query_time distribution</span><br><span class="line">#   1us</span><br><span class="line">#  10us</span><br><span class="line"># 100us</span><br><span class="line">#   1ms  ################################################################</span><br><span class="line">#  10ms</span><br><span class="line"># 100ms</span><br><span class="line">#    1s</span><br><span class="line">#  10s+</span><br><span class="line"># Tables</span><br><span class="line">#    SHOW TABLE STATUS FROM `sakila` LIKE &apos;film&apos;\G</span><br><span class="line">#    SHOW CREATE TABLE `sakila`.`film`\G</span><br><span class="line"># EXPLAIN /*!50100 PARTITIONS*/</span><br><span class="line">select * from film\G</span><br><span class="line"></span><br><span class="line"># Query 3: 0 QPS, 0x concurrency, ID 0x9134F278CE0AB549 at byte 1409 _____</span><br><span class="line"># This item is included in the report because it matches --limit.</span><br><span class="line"># Scores: V/M = 0.00</span><br><span class="line"># Time range: all events occurred at 2018-10-26 01:50:11</span><br><span class="line"># Attribute    pct   total     min     max     avg     95%  stddev  median</span><br><span class="line"># ============ === ======= ======= ======= ======= ======= ======= =======</span><br><span class="line"># Count         12       1</span><br><span class="line"># Exec time      6     2ms     2ms     2ms     2ms     2ms       0     2ms</span><br><span class="line"># Lock time     64     2ms     2ms     2ms     2ms     2ms       0     2ms</span><br><span class="line"># Rows sent      0       1       1       1       1       1       0       1</span><br><span class="line"># Rows examine   0       5       5       5       5       5       0       5</span><br><span class="line"># Query size    32      92      92      92      92      92       0      92</span><br><span class="line"># String:</span><br><span class="line"># Databases    sakila</span><br><span class="line"># Hosts        localhost</span><br><span class="line"># Users        root</span><br><span class="line"># Query_time distribution</span><br><span class="line">#   1us</span><br><span class="line">#  10us</span><br><span class="line"># 100us</span><br><span class="line">#   1ms  ################################################################</span><br><span class="line">#  10ms</span><br><span class="line"># 100ms</span><br><span class="line">#    1s</span><br><span class="line">#  10s+</span><br><span class="line"># Tables</span><br><span class="line">#    SHOW TABLE STATUS FROM `mysql` LIKE &apos;user&apos;\G</span><br><span class="line">#    SHOW CREATE TABLE `mysql`.`user`\G</span><br><span class="line"># EXPLAIN /*!50100 PARTITIONS*/</span><br><span class="line">SELECT COUNT(*), SUM(user=&quot;&quot;), SUM(password=&quot;&quot;), SUM(password NOT LIKE &quot;*%&quot;) FROM mysql.user\G</span><br><span class="line"></span><br><span class="line"># Query 4: 0.01 QPS, 0.00x concurrency, ID 0xEBA2FBA69B1FF476 at byte 0 __</span><br><span class="line"># This item is included in the report because it matches --limit.</span><br><span class="line"># Scores: V/M = 0.00</span><br><span class="line"># Time range: 2018-10-26 00:36:02 to 00:39:22</span><br><span class="line"># Attribute    pct   total     min     max     avg     95%  stddev  median</span><br><span class="line"># ============ === ======= ======= ======= ======= ======= ======= =======</span><br><span class="line"># Count         25       2</span><br><span class="line"># Exec time      4     1ms   413us   746us   579us   746us   235us   579us</span><br><span class="line"># Lock time      7   167us    51us   116us    83us   116us    45us    83us</span><br><span class="line"># Rows sent      0       2       1       1       1       1       0       1</span><br><span class="line"># Rows examine  62   1.95k    1000    1000    1000    1000       0    1000</span><br><span class="line"># Query size    17      50      25      25      25      25       0      25</span><br><span class="line"># String:</span><br><span class="line"># Databases    sakila</span><br><span class="line"># Hosts        localhost</span><br><span class="line"># Users        root</span><br><span class="line"># Query_time distribution</span><br><span class="line">#   1us</span><br><span class="line">#  10us</span><br><span class="line"># 100us  ################################################################</span><br><span class="line">#   1ms</span><br><span class="line">#  10ms</span><br><span class="line"># 100ms</span><br><span class="line">#    1s</span><br><span class="line">#  10s+</span><br><span class="line"># Tables</span><br><span class="line">#    SHOW TABLE STATUS FROM `sakila` LIKE &apos;film&apos;\G</span><br><span class="line">#    SHOW CREATE TABLE `sakila`.`film`\G</span><br><span class="line"># EXPLAIN /*!50100 PARTITIONS*/</span><br><span class="line">select count(*) from film\G</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="5、查找mysql的从库和同步状态"><a href="#5、查找mysql的从库和同步状态" class="headerlink" title="5、查找mysql的从库和同步状态"></a>5、查找mysql的从库和同步状态</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-slave-find --host=localhost --user=root --password=123456</span><br><span class="line">localhost</span><br><span class="line">Version         5.6.25</span><br><span class="line">Server ID       0</span><br><span class="line">Uptime          3+01:31:37 (started 2018-10-23T00:31:39)</span><br><span class="line">Replication     Is not a slave, has 0 slaves connected, is not read_only</span><br><span class="line">Filters         </span><br><span class="line">Binary logging  STATEMENT</span><br><span class="line">Slave status    </span><br><span class="line">Slave mode      STRICT</span><br><span class="line">Auto-increment  increment 1, offset 1</span><br><span class="line">InnoDB version  5.6.25</span><br><span class="line">[root@mysql ~]# ^C</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="6、查看mysql的死锁信息"><a href="#6、查看mysql的死锁信息" class="headerlink" title="6、查看mysql的死锁信息"></a>6、查看mysql的死锁信息</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pt-deadlock-logger --user=root --password=123456 localhost</span><br></pre></td></tr></table></figure>
<h4 id="7、从慢查询日志中分析索引使用情况"><a href="#7、从慢查询日志中分析索引使用情况" class="headerlink" title="7、从慢查询日志中分析索引使用情况"></a>7、从慢查询日志中分析索引使用情况</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-index-usage --user=root --password=123456 localhost /var/lib/mysql/mysql-slow.log </span><br><span class="line">localhost does not exist or is not readable at /usr/bin/pt-index-usage line 4447.</span><br><span class="line"></span><br><span class="line">ALTER TABLE `sakila`.`actor` DROP KEY `idx_actor_last_name`; -- type:non-unique</span><br><span class="line"></span><br><span class="line">ALTER TABLE `sakila`.`film` DROP KEY `idx_fk_original_language_id`, DROP KEY `idx_title`; -- type:non-unique</span><br><span class="line"></span><br><span class="line">ALTER TABLE `sakila`.`staff` DROP KEY `idx_fk_address_id`; -- type:non-unique</span><br></pre></td></tr></table></figure>
<h4 id="8、查找数据库表中重复的索引"><a href="#8、查找数据库表中重复的索引" class="headerlink" title="8、查找数据库表中重复的索引"></a>8、查找数据库表中重复的索引</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-duplicate-key-checker --host=localhost --user=root --password=123456</span><br><span class="line"># ########################################################################</span><br><span class="line"># menagerie.A                                                             </span><br><span class="line"># ########################################################################</span><br><span class="line"></span><br><span class="line"># id is a duplicate of PRIMARY</span><br><span class="line"># Key definitions:</span><br><span class="line">#   KEY `id` (`A_ID`)</span><br><span class="line">#   PRIMARY KEY (`A_ID`),</span><br><span class="line"># Column types:</span><br><span class="line">#         `a_id` int(11) not null auto_increment</span><br><span class="line"># To remove this duplicate index, execute:</span><br><span class="line">ALTER TABLE `menagerie`.`A` DROP INDEX `id`;</span><br><span class="line"></span><br><span class="line"># ########################################################################</span><br><span class="line"># Summary of indexes                                                      </span><br><span class="line"># ########################################################################</span><br><span class="line"></span><br><span class="line"># Size Duplicate Indexes   12</span><br><span class="line"># Total Duplicate Indexes  1</span><br><span class="line"># Total Indexes            99</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="9、查看mysql表和文件的当前活动IO开销"><a href="#9、查看mysql表和文件的当前活动IO开销" class="headerlink" title="9、查看mysql表和文件的当前活动IO开销"></a>9、查看mysql表和文件的当前活动IO开销</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-ioprofile</span><br><span class="line">Fri Oct 26 02:14:17 CST 2018</span><br><span class="line">Tracing process ID 37860</span><br><span class="line">     total filename</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="10、查看不同mysql配置文件的差异"><a href="#10、查看不同mysql配置文件的差异" class="headerlink" title="10、查看不同mysql配置文件的差异"></a>10、查看不同mysql配置文件的差异</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-config-diff /etc/my.cnf /etc/my_master.cnf</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="11、pt-find查找mysql表和执行命令，示例如下"><a href="#11、pt-find查找mysql表和执行命令，示例如下" class="headerlink" title="11、pt-find查找mysql表和执行命令，示例如下"></a>11、pt-find查找mysql表和执行命令，示例如下</h4><p>查找数据库里大于2G的表：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-find --user=root --password=123456 --tablesize +2G</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<p>查找10天前创建，MyISAM引擎的表：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-find --user=root --password=123456 --ctime +10 --engine MyISAM</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<p>查看表和索引大小并排序</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-find --user=root --password=123456 --printf &quot;%T\t%D.%N\n&quot; | sort -rn</span><br><span class="line">2785280 `sakila`.`rental`</span><br><span class="line">2228224 `sakila`.`payment`</span><br><span class="line">588216  `mysql`.`help_topic`</span><br><span class="line">376832  `sakila`.`inventory`</span><br><span class="line">278528  `sakila`.`film_actor`</span><br><span class="line">278528  `sakila`.`film`</span><br><span class="line">196608  `sakila`.`film_text`</span><br><span class="line">141280  `mysql`.`help_keyword`</span><br><span class="line">131072  `sakila`.`customer`</span><br><span class="line">98304   `sakila`.`staff`</span><br><span class="line">98304   `sakila`.`address`</span><br><span class="line">81920   `sakila`.`film_category`</span><br><span class="line">65536   `sakila`.`city`</span><br><span class="line">49152   `sakila`.`store`</span><br><span class="line">49152   `mysql`.`innodb_index_stats`</span><br><span class="line">33463   `mysql`.`help_relation`</span><br><span class="line">32768   `sakila`.`actor`</span><br><span class="line">16384   `sakila`.`language`</span><br><span class="line">16384   `sakila`.`country`</span><br><span class="line">16384   `sakila`.`category`</span><br><span class="line">16384   `mysql`.`slave_worker_info`</span><br><span class="line">16384   `mysql`.`slave_relay_log_info`</span><br><span class="line">16384   `mysql`.`slave_master_info`</span><br><span class="line">16384   `mysql`.`innodb_table_stats`</span><br><span class="line">16384   `menagerie`.`shop`</span><br><span class="line">16384   `menagerie`.`pet`</span><br><span class="line">16384   `menagerie`.`employee_tbl`</span><br><span class="line">16384   `menagerie`.`employee`</span><br><span class="line">16384   `menagerie`.`B`</span><br><span class="line">16384   `menagerie`.`A`</span><br><span class="line">16384   `test22`.`shop`</span><br><span class="line">16384   `test22`.`pet`</span><br><span class="line">16384   `test22`.`B`</span><br><span class="line">16384   `test22`.`A`</span><br><span class="line">12388   `mysql`.`proc`</span><br><span class="line">6506    `mysql`.`proxies_priv`</span><br><span class="line">6000    `mysql`.`db`</span><br><span class="line">4192    `mysql`.`help_category`</span><br><span class="line">4096    `mysql`.`tables_priv`</span><br><span class="line">4096    `mysql`.`procs_priv`</span><br><span class="line">4096    `mysql`.`columns_priv`</span><br><span class="line">2692    `mysql`.`user`</span><br><span class="line">2048    `mysql`.`event`</span><br><span class="line">1024    `mysql`.`time_zone_transition_type`</span><br><span class="line">1024    `mysql`.`time_zone_transition`</span><br><span class="line">1024    `mysql`.`time_zone_name`</span><br><span class="line">1024    `mysql`.`time_zone_leap_second`</span><br><span class="line">1024    `mysql`.`time_zone`</span><br><span class="line">1024    `mysql`.`servers`</span><br><span class="line">1024    `mysql`.`plugin`</span><br><span class="line">1024    `mysql`.`ndb_binlog_index`</span><br><span class="line">1024    `mysql`.`func`</span><br><span class="line">0       `sakila`.`staff_list`</span><br><span class="line">0       `sakila`.`sales_by_store`</span><br><span class="line">0       `sakila`.`sales_by_film_category`</span><br><span class="line">0       `sakila`.`nicer_but_slower_film_list`</span><br><span class="line">0       `sakila`.`film_list`</span><br><span class="line">0       `sakila`.`customer_list`</span><br><span class="line">0       `sakila`.`actor_info`</span><br><span class="line">0       `performance_schema`.`users`</span><br><span class="line">0       `performance_schema`.`threads`</span><br><span class="line">0       `performance_schema`.`table_lock_waits_summary_by_table`</span><br><span class="line">0       `performance_schema`.`table_io_waits_summary_by_table`</span><br><span class="line">0       `performance_schema`.`table_io_waits_summary_by_index_usage`</span><br><span class="line">0       `performance_schema`.`socket_summary_by_instance`</span><br><span class="line">0       `performance_schema`.`socket_summary_by_event_name`</span><br><span class="line">0       `performance_schema`.`socket_instances`</span><br><span class="line">0       `performance_schema`.`setup_timers`</span><br><span class="line">0       `performance_schema`.`setup_objects`</span><br><span class="line">0       `performance_schema`.`setup_instruments`</span><br><span class="line">0       `performance_schema`.`setup_consumers`</span><br><span class="line">0       `performance_schema`.`setup_actors`</span><br><span class="line">0       `performance_schema`.`session_connect_attrs`</span><br><span class="line">0       `performance_schema`.`session_account_connect_attrs`</span><br><span class="line">0       `performance_schema`.`rwlock_instances`</span><br><span class="line">0       `performance_schema`.`performance_timers`</span><br><span class="line">0       `performance_schema`.`objects_summary_global_by_type`</span><br><span class="line">0       `performance_schema`.`mutex_instances`</span><br><span class="line">0       `performance_schema`.`hosts`</span><br><span class="line">0       `performance_schema`.`host_cache`</span><br><span class="line">0       `performance_schema`.`file_summary_by_instance`</span><br><span class="line">0       `performance_schema`.`file_summary_by_event_name`</span><br><span class="line">0       `performance_schema`.`file_instances`</span><br><span class="line">0       `performance_schema`.`events_waits_summary_global_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_waits_summary_by_user_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_waits_summary_by_thread_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_waits_summary_by_instance`</span><br><span class="line">0       `performance_schema`.`events_waits_summary_by_host_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_waits_summary_by_account_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_waits_history_long`</span><br><span class="line">0       `performance_schema`.`events_waits_history`</span><br><span class="line">0       `performance_schema`.`events_waits_current`</span><br><span class="line">0       `performance_schema`.`events_statements_summary_global_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_statements_summary_by_user_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_statements_summary_by_thread_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_statements_summary_by_host_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_statements_summary_by_digest`</span><br><span class="line">0       `performance_schema`.`events_statements_summary_by_account_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_statements_history_long`</span><br><span class="line">0       `performance_schema`.`events_statements_history`</span><br><span class="line">0       `performance_schema`.`events_statements_current`</span><br><span class="line">0       `performance_schema`.`events_stages_summary_global_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_stages_summary_by_user_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_stages_summary_by_thread_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_stages_summary_by_host_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_stages_summary_by_account_by_event_name`</span><br><span class="line">0       `performance_schema`.`events_stages_history_long`</span><br><span class="line">0       `performance_schema`.`events_stages_history`</span><br><span class="line">0       `performance_schema`.`events_stages_current`</span><br><span class="line">0       `performance_schema`.`cond_instances`</span><br><span class="line">0       `performance_schema`.`accounts`</span><br><span class="line">0       `mysql`.`slow_log`</span><br><span class="line">0       `mysql`.`general_log`</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="12、pt-kill-杀掉符合标准的mysql进程"><a href="#12、pt-kill-杀掉符合标准的mysql进程" class="headerlink" title="12、pt-kill 杀掉符合标准的mysql进程"></a>12、pt-kill 杀掉符合标准的mysql进程</h4><p>显示查询时间大于60秒的查询</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-kill --user=root --password=123456 --busy-time 60 --print</span><br><span class="line">^C</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<p>kill掉大于60秒的查询</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pt-kill --user=root --password=123456 --busy-time 60 --kill</span><br></pre></td></tr></table></figure>
<h4 id="13、查看mysql授权"><a href="#13、查看mysql授权" class="headerlink" title="13、查看mysql授权"></a>13、查看mysql授权</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">^C</span><br><span class="line">[root@mysql ~]# pt-show-grants --user=root --password=123456</span><br><span class="line">-- Grants dumped by pt-show-grants</span><br><span class="line">-- Dumped from server Localhost via UNIX socket, MySQL 5.6.25 at 2018-10-26 02:45:29</span><br><span class="line">-- Grants for &apos;root&apos;@&apos;%&apos;</span><br><span class="line">GRANT ALL PRIVILEGES ON *.* TO &apos;root&apos;@&apos;%&apos; IDENTIFIED BY PASSWORD &apos;*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9&apos;;</span><br><span class="line">-- Grants for &apos;root&apos;@&apos;127.0.0.1&apos;</span><br><span class="line">GRANT ALL PRIVILEGES ON *.* TO &apos;root&apos;@&apos;127.0.0.1&apos; IDENTIFIED BY PASSWORD &apos;*6E666163AC88D2C7122156EB3B633E3172F24604&apos; WITH GRANT OPTION;</span><br><span class="line">-- Grants for &apos;root&apos;@&apos;::1&apos;</span><br><span class="line">GRANT ALL PRIVILEGES ON *.* TO &apos;root&apos;@&apos;::1&apos; IDENTIFIED BY PASSWORD &apos;*6E666163AC88D2C7122156EB3B633E3172F24604&apos; WITH GRANT OPTION;</span><br><span class="line">-- Grants for &apos;root&apos;@&apos;localhost&apos;</span><br><span class="line">GRANT ALL PRIVILEGES ON *.* TO &apos;root&apos;@&apos;localhost&apos; IDENTIFIED BY PASSWORD &apos;*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9&apos; WITH GRANT OPTION;</span><br><span class="line">GRANT PROXY ON &apos;&apos;@&apos;&apos; TO &apos;root&apos;@&apos;localhost&apos; WITH GRANT OPTION;</span><br><span class="line">-- Grants for &apos;root&apos;@&apos;mysql&apos;</span><br><span class="line">GRANT ALL PRIVILEGES ON *.* TO &apos;root&apos;@&apos;mysql&apos; IDENTIFIED BY PASSWORD &apos;*6E666163AC88D2C7122156EB3B633E3172F24604&apos; WITH GRANT OPTION;</span><br><span class="line">GRANT PROXY ON &apos;&apos;@&apos;&apos; TO &apos;root&apos;@&apos;mysql&apos; WITH GRANT OPTION;</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="14、验证数据库复制的完整性"><a href="#14、验证数据库复制的完整性" class="headerlink" title="14、验证数据库复制的完整性"></a>14、验证数据库复制的完整性</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql ~]# pt-table-checksum --user=root --password=123456</span><br><span class="line">Diffs cannot be detected because no slaves were found.  Please read the --recursion-method documentation for information.</span><br><span class="line">            TS ERRORS  DIFFS     ROWS  CHUNKS SKIPPED    TIME TABLE</span><br><span class="line">10-26T02:47:01      0      0        3       1       0   0.010 test22.A</span><br><span class="line">10-26T02:47:01      0      0        3       1       0   0.011 test22.B</span><br><span class="line">10-26T02:47:01      0      0        8       1       0   0.025 test22.pet</span><br><span class="line">10-26T02:47:01      0      0        7       1       0   0.011 test22.shop</span><br><span class="line">10-26T02:47:01      0      0        3       1       0   0.008 menagerie.A</span><br><span class="line">10-26T02:47:01      0      0        3       1       0   0.007 menagerie.B</span><br><span class="line">10-26T02:47:01      0      0        9       1       0   0.011 menagerie.employee</span><br><span class="line">10-26T02:47:01      0      0        6       1       0   0.026 menagerie.employee_tbl</span><br><span class="line">10-26T02:47:01      0      0        8       1       0   0.007 menagerie.pet</span><br><span class="line">10-26T02:47:01      0      0        7       1       0   0.006 menagerie.shop</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.007 mysql.columns_priv</span><br><span class="line">10-26T02:47:01      0      0        2       1       0   0.008 mysql.db</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.006 mysql.event</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.006 mysql.func</span><br><span class="line">10-26T02:47:01      0      0       40       1       0   0.023 mysql.help_category</span><br><span class="line">10-26T02:47:01      0      0      608       1       0   0.010 mysql.help_keyword</span><br><span class="line">10-26T02:47:01      0      0     1215       1       0   0.018 mysql.help_relation</span><br><span class="line">10-26T02:47:01      0      0      583       1       0   0.039 mysql.help_topic</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.008 mysql.ndb_binlog_index</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.007 mysql.plugin</span><br><span class="line">10-26T02:47:01      0      0        6       1       0   0.007 mysql.proc</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.010 mysql.procs_priv</span><br><span class="line">10-26T02:47:01      0      0        2       1       0   0.007 mysql.proxies_priv</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.027 mysql.servers</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.007 mysql.tables_priv</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.008 mysql.time_zone</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.009 mysql.time_zone_leap_second</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.008 mysql.time_zone_name</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.010 mysql.time_zone_transition</span><br><span class="line">10-26T02:47:01      0      0        0       1       0   0.011 mysql.time_zone_transition_type</span><br><span class="line">10-26T02:47:01      0      0        5       1       0   0.031 mysql.user</span><br><span class="line">10-26T02:47:01      0      0      200       1       0   0.010 sakila.actor</span><br><span class="line">10-26T02:47:01      0      0      603       1       0   0.013 sakila.address</span><br><span class="line">10-26T02:47:01      0      0       16       1       0   0.011 sakila.category</span><br><span class="line">10-26T02:47:01      0      0      600       1       0   0.012 sakila.city</span><br><span class="line">10-26T02:47:01      0      0      109       1       0   0.014 sakila.country</span><br><span class="line">10-26T02:47:01      0      0      599       1       0   0.011 sakila.customer</span><br><span class="line">10-26T02:47:01      0      0     1000       1       0   0.016 sakila.film</span><br><span class="line">10-26T02:47:01      0      0     5462       1       0   0.020 sakila.film_actor</span><br><span class="line">10-26T02:47:01      0      0     1000       1       0   0.013 sakila.film_category</span><br><span class="line">10-26T02:47:01      0      0     1000       1       0   0.013 sakila.film_text</span><br><span class="line">10-26T02:47:01      0      0     4581       1       0   0.058 sakila.inventory</span><br><span class="line">10-26T02:47:01      0      0        6       1       0   0.008 sakila.language</span><br><span class="line">10-26T02:47:01      0      0    16049       1       0   0.059 sakila.payment</span><br><span class="line">10-26T02:47:02      0      0    16044       1       0   0.069 sakila.rental</span><br><span class="line">10-26T02:47:02      0      0        2       1       0   0.008 sakila.staff</span><br><span class="line">10-26T02:47:02      0      0        2       1       0   0.011 sakila.store</span><br><span class="line">[root@mysql ~]#</span><br></pre></td></tr></table></figure>
<h4 id="15、附录："><a href="#15、附录：" class="headerlink" title="15、附录："></a>15、附录：</h4><p><img src="file:///C:/Users/Deborah/AppData/Local/Temp/msohtmlclip1/01/clip_image020.png" alt=""></p>
<h1 id="6、如何通过慢查日志发现有问题的SQL"><a href="#6、如何通过慢查日志发现有问题的SQL" class="headerlink" title="6、如何通过慢查日志发现有问题的SQL"></a>6、如何通过慢查日志发现有问题的SQL</h1><h2 id="1、查询次数多且每次查询占用时间长的sql"><a href="#1、查询次数多且每次查询占用时间长的sql" class="headerlink" title="1、查询次数多且每次查询占用时间长的sql"></a>1、查询次数多且每次查询占用时间长的sql</h2><p>通常为pt-query-digest分析的前几个查询；该工具可以很清楚的看出每个SQL执行的次数及百分比等信息，执行的次数多，占比比较大的SQL</p>
<h2 id="2、IO大的sql"><a href="#2、IO大的sql" class="headerlink" title="2、IO大的sql"></a>2、IO大的sql</h2><pre><code>注意pt-query-digest分析中的Rows examine项。扫描的行数越多，IO越大。
</code></pre><h2 id="3、未命中的索引的SQL"><a href="#3、未命中的索引的SQL" class="headerlink" title="3、未命中的索引的SQL"></a>3、未命中的索引的SQL</h2><pre><code>注意pt-query-digest分析中的Rows examine 和Rows Send的对比。说明该SQL的索引命中率不高，对于这种SQL，我们要重点进行关注。
</code></pre><h1 id="7、通过explain查询分析SQL的执行计划"><a href="#7、通过explain查询分析SQL的执行计划" class="headerlink" title="7、通过explain查询分析SQL的执行计划"></a>7、通过explain查询分析SQL的执行计划</h1><h2 id="1、使用explain查询SQL的执行计划"><a href="#1、使用explain查询SQL的执行计划" class="headerlink" title="1、使用explain查询SQL的执行计划"></a>1、使用explain查询SQL的执行计划</h2><p>SQL的执行计划侧面反映出了SQL的执行效率，具体执行方式如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">EXPLAIN SELECT * FROM `user`</span><br><span class="line">  JOIN `post` ON `user`.id = `post`.uid</span><br><span class="line">WHERE user.`created_at` &lt; &apos;2018-10-01 00:00:00&apos; AND `post`.status = 1;</span><br></pre></td></tr></table></figure>
<p>在执行的SQL前面加上explain关键词即可；</p>
<h2 id="2、每个字段的说明："><a href="#2、每个字段的说明：" class="headerlink" title="2、每个字段的说明："></a>2、每个字段的说明：</h2><p>1）id列数字越大越先执行，如果说数字一样大，那么就从上往下依次执行，id列为null的就表是这是一个结果集，不需要使用它来进行查询。</p>
<p>2）select_type列常见的有：</p>
<p>A：simple：表示不需要union操作或者不包含子查询的简单select查询。有连接查询时，外层的查询为simple，且只有一个</p>
<p>B：primary：一个需要union操作或者含有子查询的select，位于最外层的单位查询的select_type即为primary。且只有一个</p>
<p>C：union：union连接的两个select查询，第一个查询是dervied派生表，除了第一个表外，第二个以后的表select_type都是union</p>
<p>D：dependent union：与union一样，出现在union 或unionall语句中，但是这个查询要受到外部查询的影响</p>
<p>E：union result：包含union的结果集，在union和unionall语句中,因为它不需要参与查询，所以id字段为null</p>
<p>F：subquery：除了from字句中包含的子查询外，其他地方出现的子查询都可能是subquery</p>
<p>G：dependentsubquery：与dependent union类似，表示这个subquery的查询要受到外部表查询的影响</p>
<p>H：derived：from字句中出现的子查询，也叫做派生表，其他数据库中可能叫做内联视图或嵌套select</p>
<p>3）table</p>
<p>显示的查询表名，如果查询使用了别名，那么这里显示的是别名，如果不涉及对数据表的操作，那么这显示为null，如果显示为尖括号括起来的<derived n="">就表示这个是临时表，后边的N就是执行计划中的id，表示结果来自于这个查询产生。如果是尖括号括起来的<union m,n="">，与<derived n="">类似，也是一个临时表，表示这个结果来自于union查询的id为M,N的结果集。</derived></union></derived></p>
<p>4）type</p>
<p>依次从好到差：system，const，eq_ref，ref，fulltext，ref_or_null，unique_subquery，index_subquery，range，index_merge，index，ALL，除了all之外，其他的type都可以使用到索引，除了index_merge之外，其他的type只可以用到一个索引</p>
<p>A：system：表中只有一行数据或者是空表，且只能用于myisam和memory表。如果是Innodb引擎表，type列在这个情况通常都是all或者index</p>
<p>B：const：使用唯一索引或者主键，返回记录一定是1行记录的等值where条件时，通常type是const。其他数据库也叫做唯一索引扫描</p>
<p>C：eq_ref：出现在要连接过个表的查询计划中，驱动表只返回一行数据，且这行数据是第二个表的主键或者唯一索引，且必须为not null，唯一索引和主键是多列时，只有所有的列都用作比较时才会出现eq_ref</p>
<p>D：ref：不像eq_ref那样要求连接顺序，也没有主键和唯一索引的要求，只要使用相等条件检索时就可能出现，常见与辅助索引的等值查找。或者多列主键、唯一索引中，使用第一个列之外的列作为等值查找也会出现，总之，返回数据不唯一的等值查找就可能出现。</p>
<p>E：fulltext：全文索引检索，要注意，全文索引的优先级很高，若全文索引和普通索引同时存在时，mysql不管代价，优先选择使用全文索引</p>
<p>F：ref_or_null：与ref方法类似，只是增加了null值的比较。实际用的不多。</p>
<p>G：unique_subquery：用于where中的in形式子查询，子查询返回不重复值唯一值</p>
<p>H：index_subquery：用于in形式子查询使用到了辅助索引或者in常数列表，子查询可能返回重复值，可以使用索引将子查询去重。</p>
<p>I：range：索引范围扫描，常见于使用&gt;,&lt;,is null,between ,in ,like等运算符的查询中。</p>
<p>J：index_merge：表示查询使用了两个以上的索引，最后取交集或者并集，常见and ，or的条件使用了不同的索引，官方排序这个在ref_or_null之后，但是实际上由于要读取所个索引，性能可能大部分时间都不如range</p>
<p>K：index：索引全表扫描，把索引从头到尾扫一遍，常见于使用索引列就可以处理不需要读取数据文件的查询、可以使用索引排序或者分组的查询。 </p>
<p>L：all：这个就是全表扫描数据文件，然后再在server层进行过滤返回符合要求的记录。</p>
<p>5）possible_keys</p>
<p>查询可能使用到的索引都会在这里列出来</p>
<p>6）key</p>
<p>查询真正使用到的索引，select_type为index_merge时，这里可能出现两个以上的索引，其他的select_type这里只会出现一个。</p>
<p>7）key_len</p>
<p>用于处理查询的索引长度，如果是单列索引，那就整个索引长度算进去，如果是多列索引，那么查询不一定都能使用到所有的列，具体使用到了多少个列的索引，这里就会计算进去，没有使用到的列，这里不会计算进去。留意下这个列的值，算一下你的多列索引总长度就知道有没有使用到所有的列了。要注意，mysql的ICP特性使用到的索引不会计入其中。另外，key_len只计算where条件用到的索引长度，而排序和分组就算用到了索引，也不会计算到key_len中。</p>
<p>8）ref</p>
<p>如果是使用的常数等值查询，这里会显示const，如果是连接查询，被驱动表的执行计划这里会显示驱动表的关联字段，如果是条件使用了表达式或者函数，或者条件列发生了内部隐式转换，这里可能显示为func</p>
<p>9）rows</p>
<p>这里是执行计划中估算的扫描行数，不是精确值</p>
<p>10）extra</p>
<p>这个列可以显示的信息非常多，有几十种，常用的有</p>
<p>A：distinct：在select部分使用了distinc关键字</p>
<p>B：no tables used：不带from字句的查询或者From dual查询</p>
<p>C：使用not in()形式子查询或not exists运算符的连接查询，这种叫做反连接。即，一般连接查询是先查询内表，再查询外表，反连接就是先查询外表，再查询内表。</p>
<p>D：using filesort：排序时无法使用到索引时，就会出现这个。常见于order by和group by语句中</p>
<p>E：using index：查询时不需要回表查询，直接通过索引就可以获取查询的数据。</p>
<p>F：using join buffer（block nested loop），using join buffer（batched key accss）：5.6.x之后的版本优化关联查询的BNL，BKA特性。主要是减少内表的循环数量以及比较顺序地扫描查询。</p>
<p>G：using sort_union，using_union，using intersect，using sort_intersection：</p>
<p>using intersect：表示使用and的各个索引的条件时，该信息表示是从处理结果获取交集</p>
<p>using union：表示使用or连接各个使用索引的条件时，该信息表示从处理结果获取并集</p>
<p>using sort_union和usingsort_intersection：与前面两个对应的类似，只是他们是出现在用and和or查询信息量大时，先查询主键，然后进行排序合并后，才能读取记录并返回。</p>
<p>H：using temporary：表示使用了临时表存储中间结果。临时表可以是内存临时表和磁盘临时表，执行计划中看不出来，需要查看status变量，used_tmp_table，used_tmp_disk_table才能看出来。</p>
<p>I：using where：表示存储引擎返回的记录并不是所有的都满足查询条件，需要在server层进行过滤。查询条件中分为限制条件和检查条件，5.6之前，存储引擎只能根据限制条件扫描数据并返回，然后server层根据检查条件进行过滤再返回真正符合查询的数据。5.6.x之后支持ICP特性，可以把检查条件也下推到存储引擎层，不符合检查条件和限制条件的数据，直接不读取，这样就大大减少了存储引擎扫描的记录数量。extra列显示using index condition</p>
<p>J：firstmatch(tb_name)：5.6.x开始引入的优化子查询的新特性之一，常见于where字句含有in()类型的子查询。如果内表的数据量比较大，就可能出现这个</p>
<p>K：loosescan(m..n)：5.6.x之后引入的优化子查询的新特性之一，在in()类型的子查询中，子查询返回的可能有重复记录时，就可能出现这个</p>
<p>除了这些之外，还有很多查询数据字典库，执行计划过程中就发现不可能存在结果的一些提示信息</p>
<p>11）filtered</p>
<p>使用explain extended时会出现这个列，5.7之后的版本默认就有这个字段，不需要使用explain extended了。这个字段表示存储引擎返回的数据在server层过滤后，剩下多少满足查询的记录数量的比例，注意是百分比，不是具体记录数。</p>
<h2 id="3-具体慢查询的优化案例"><a href="#3-具体慢查询的优化案例" class="headerlink" title="3  具体慢查询的优化案例"></a>3  具体慢查询的优化案例</h2><h3 id="1、Limit查询的优化"><a href="#1、Limit查询的优化" class="headerlink" title="1、Limit查询的优化"></a>1、Limit查询的优化</h3><p>Limit常用于分页处理，时长会伴随orderby从句使用，因此大多时候回使用Filesorts这样会造成大量的IO问题。</p>
<p>优化步骤1：</p>
<p>使用有索引的列或主键进行order by操作，因为大家知道，innodb是按照主键的逻辑顺序进行排序的。可以避免很多的IO操作。</p>
<p>优化步骤2、记录上次返回的主键， 在下次查询时使用主键过滤。（说明：避免了数据量大时扫描过多的记录）</p>
<p>注意事项：</p>
<p>主键要顺序排序并连续的，如果主键中间空缺了某一列，或者某几列，会出现列出数据不足5行的数据；如果不连续的情况，建立一个附加的列index_id列，保证这一列数据要自增的，并添加索引即可。</p>
<h3 id="2、索引的优化"><a href="#2、索引的优化" class="headerlink" title="2、索引的优化"></a>2、索引的优化</h3><h4 id="1、什么是索引？"><a href="#1、什么是索引？" class="headerlink" title="1、什么是索引？"></a>1、什么是索引？</h4><p>索引的作用相当于图书的目录，可以根据目录中的页码快速找到所需的内容。</p>
<p>数据库使用索引以找到特定值，然后顺指针找到包含该值的行。在表中建立索引，然后在索引中找到符合查询条件的索引值，最后通过保存在索引中的ROWID（相当于页码）快速找到表中对应的记录。索引的建立是表中比较有指向性的字段，相当于目录，比如说行政区域代码，同一个地域的行政区域代码都是相同的，那么给这一列加上索引，避免让它重复扫描，从而达到优化的目的！</p>
<h4 id="2、如何创建索引"><a href="#2、如何创建索引" class="headerlink" title="2、如何创建索引"></a>2、如何创建索引</h4><p>在执行CREATE TABLE语句时可以创建索引，也可以单独用CREATE INDEX或ALTER TABLE来为表增加索引。</p>
<pre><code>1、ALTER TABLE
</code></pre><p>ALTER TABLE用来创建普通索引、UNIQUE索引或PRIMARY KEY索引。</p>
<p>ALTER TABLE table_name ADDINDEX index_name (column_list)</p>
<p>ALTER TABLE table_name ADDUNIQUE (column_list)</p>
<p>ALTER TABLE table_name ADDPRIMARY KEY (column_list)</p>
<p>说明：其中table_name是要增加索引的表名，column_list指出对哪些列进行索引，多列时各列之间用逗号分隔。索引名index_name可选，缺省时，MySQL将根据第一个索引列赋一个名称。另外，ALTER TABLE允许在单个语句中更改多个表，因此可以在同时创建多个索引。</p>
<pre><code>2、CREATE INDEX
</code></pre><p>CREATE INDEX可对表增加普通索引或UNIQUE索引。</p>
<p>CREATE INDEX index_name ONtable_name (column_list)</p>
<p>CREATE UNIQUE INDEXindex_name ON table_name (column_list)</p>
<pre><code>说明：table_name、index_name和column_list具有与ALTER TABLE语句中相同的含义，索引名不可选。另外，不能用CREATE INDEX语句创建PRIMARY KEY索引。



3、索引类型
</code></pre><p>在创建索引时，可以规定索引能否包含重复值。如果不包含，则索引应该创建为PRIMARY KEY或UNIQUE索引。对于单列惟一性索引，这保证单列不包含重复的值。对于多列惟一性索引，保证多个值的组合不重复。</p>
<p>PRIMARY KEY索引和UNIQUE索引非常类似。</p>
<p>事实上，PRIMARY KEY索引仅是一个具有名称PRIMARY的UNIQUE索引。这表示一个表只能包含一个PRIMARY KEY，因为一个表中不可能具有两个同名的索引。</p>
<p>下面的SQL语句对students表在sid上添加PRIMARYKEY索引。</p>
<p>ALTER TABLE students ADDPRIMARY KEY (sid)</p>
<pre><code>4、删除索引

       可利用ALTER TABLE或DROPINDEX语句来删除索引。类似于CREATE INDEX语句，DROPINDEX可以在ALTER TABLE内部作为一条语句处理，语法如下。
</code></pre><p>DROP INDEX index_name ONtalbe_name</p>
<p>ALTER TABLE table_name DROPINDEX index_name</p>
<p>ALTER TABLE table_name DROPPRIMARY KEY</p>
<p>其中，前两条语句是等价的，删除掉table_name中的索引index_name。</p>
<p>第3条语句只在删除PRIMARYKEY索引时使用，因为一个表只可能有一个PRIMARY KEY索引，因此不需要指定索引名。如果没有创建PRIMARY KEY索引，但表具有一个或多个UNIQUE索引，则MySQL将删除第一个UNIQUE索引。</p>
<p>如果从表中删除了某列，则索引会受到影响。对于多列组合的索引，如果删除其中的某列，则该列也会从索引中删除。如果删除组成索引的所有列，则整个索引将被删除。</p>
<p>   5、查看索引</p>
<p>   6、什么情况下，使用索引了？</p>
<pre><code>1、表的主关键字
</code></pre><p>2、自动建立唯一索引</p>
<p>3、表的字段唯一约束</p>
<p>4、直接条件查询的字段（在SQL中用于条件约束的字段）</p>
<p>5、查询中与其它表关联的字段</p>
<p>6、查询中排序的字段（排序的字段如果通过索引去访问那将大大提高排序速度）</p>
<p>7、查询中统计或分组统计的字段</p>
<p>8、表记录太少（如果一个表只有5条记录，采用索引去访问记录的话，那首先需访问索引表，再通过索引表访问数据表，一般索引表与数据表不在同一个数据块）</p>
<p>9、经常插入、删除、修改的表（对一些经常处理的业务表应在查询允许的情况下尽量减少索引）</p>
<p>10、数据重复且分布平均的表字段（假如一个表有10万行记录，有一个字段A只有T和F两种值，且每个值的分布概率大约为50%，那么对这种表A字段建索引一般不会提高数据库的查询速度。）</p>
<p>11、经常和主字段一块查询但主字段索引值比较多的表字段</p>
<p>12、对千万级MySQL数据库建立索引的事项及提高性能的手段</p>
<h4 id="3、如何选择合适的列建立索引"><a href="#3、如何选择合适的列建立索引" class="headerlink" title="3、如何选择合适的列建立索引"></a>3、如何选择合适的列建立索引</h4><pre><code>1、在where从句，group by从句，order by从句，on从句中虚线的列添加索引

2、索引字段越小越好（因为数据库数据存储单位是以“页”为单位的，数据存储的越多，IO也会越大）
</code></pre><p>3、离散度大的列放到联合索引的前面</p>
<p>例子：</p>
<p>注意:</p>
<pre><code>是index（staff_id，customer_id）好，还是index（customer_id，staff_id）好
</code></pre><p>那我们怎么进行验证离散度好了？</p>
<p>A、我们先查看一下表结构</p>
<p><img src="file:///C:/Users/Deborah/AppData/Local/Temp/msohtmlclip1/01/clip_image087.jpg" alt=""></p>
<p>B、分别查看这两个字段中不同的id的数量，数量越多，则表明离散程度越大：因此可以通过下图看出：customer_id 离散程度大。</p>
<p><img src="file:///C:/Users/Deborah/AppData/Local/Temp/msohtmlclip1/01/clip_image089.jpg" alt=""></p>
<p>结论：由于customer_id 离散程度大，使用index（customer_id，staff_id）好</p>
<p>C、mysql联合索引</p>
<p>①命名规则 ：表名_字段名</p>
<pre><code>1、需要加索引的字段，要在where条件中
</code></pre><p>2、数据量少的字段不需要加索引</p>
<p>3、如果where条件中是OR关系，加索引不起作用</p>
<p>4、符合最左原则</p>
<p>②什么是联合索引</p>
<p>1、两个或更多个列上的索引被称作联合索引，又被称为是复合索引。</p>
<p>2、利用索引中的附加列，您可以缩小搜索的范围，但使用一个具有两列的索引不同于使用两个单独的索引。复合索引的结构与电话簿类似，人名由姓和名构成，电话簿首先按姓氏对进行排序，然后按名字对有相同姓氏的人进行排序。如果您知 道姓，电话簿将非常有用；如果您知道姓和名，电话簿则更为有用，但如果您只知道名不姓，电话簿将没有用处。</p>
<p>所以说创建复合索引时，应该仔细考虑列的顺序。对索引中的所有列执行搜索或仅对前几列执行搜索时，复合索引非常有用；仅对后面的任意列执行搜索时，复合索引则没有用处。</p>
<h4 id="4、索引优化SQL的方法"><a href="#4、索引优化SQL的方法" class="headerlink" title="4、索引优化SQL的方法"></a>4、索引优化SQL的方法</h4><p>1、索引的维护及优化（重复及冗余索引）</p>
<pre><code>增加索引会有利于查询效率，但会降低insert，update，delete的效率，但实际上往往不是这样的，过多的索引会不但会影响使用效率，同时会影响查询效率，这是由于数据库进行查询分析时，首先要选择使用哪一个索引进行查询，如果索引过多，分析过程就会越慢，这样同样的减少查询的效率，因此我们要知道如何增加，有时候要知道维护和删除不需要的索引
</code></pre><p>2、如何找到重复和冗余的索引</p>
<p>重复索引：</p>
<p>重复索引是指相同的列以相同的顺序简历的同类型的索引，如下表中的 primary key和ID列上的索引就是重复索引</p>
<p>冗余索引：</p>
<pre><code>冗余索引是指多个索引的前缀列相同，或是在联合索引中包含了主键的索引，下面这个例子中key（name，id）就是一个冗余索引。
</code></pre><p>说明：对于innodb来说，每一个索引后面，实际上都会包含主键，这时候我们建立的联合索引，又人为的把主键包含进去，那么这个时候就是一个冗余索引。</p>
<p>3、如何查找重复索引</p>
<p>工具：使用pt-duplicate-key-checker工具检查重复及冗余索引</p>
<p><img src="file:///C:/Users/Deborah/AppData/Local/Temp/msohtmlclip1/01/clip_image091.jpg" alt=""></p>
<p>4、索引维护的方法</p>
<pre><code>由于业务变更，某些索引是后续不需要使用的，就要进行杀出。
</code></pre><p>在mysql中，目前只能通过慢查询日志配合pt-index-usage工具来进行索引使用情况的分析；</p>
<p><img src="file:///C:/Users/Deborah/AppData/Local/Temp/msohtmlclip1/01/clip_image093.jpg" alt=""></p>
<p>附：<a href="https://www.percona.com/downloads/" target="_blank" rel="noopener">https://www.percona.com/downloads/</a></p>
<h4 id="5、注意事项"><a href="#5、注意事项" class="headerlink" title="5、注意事项"></a>5、注意事项</h4><p>设计好MySql的索引可以让你的数据库飞起来，大大的提高数据库效率。设计MySql索引的时候有一下几点注意：</p>
<p>1，创建索引</p>
<p>对于查询占主要的应用来说，索引显得尤为重要。很多时候性能问题很简单的就是因为我们忘了添加索引而造成的，或者说没有添加更为有效的索引导致。如果不加</p>
<p>索引的话，那么查找任何哪怕只是一条特定的数据都会进行一次全表扫描，如果一张表的数据量很大而符合条件的结果又很少，那么不加索引会引起致命的性能下降。</p>
<p>但是也不是什么情况都非得建索引不可，比如性别可能就只有两个值，建索引不仅没什么优势，还会影响到更新速度，这被称为过度索引。</p>
<p>2，复合索引</p>
<p>比如有一条语句是这样的：select * from users where area=’beijing’ and age=22;</p>
<p>如果我们是在area和age上分别创建单个索引的话，由于mysql查询每次只能使用一个索引，所以虽然这样已经相对不做索引时全表扫描提高了很多效</p>
<p>率，但是如果在area、age两列上创建复合索引的话将带来更高的效率。如果我们创建了(area, age,salary)的复合索引，那么其实相当于创建了(area,age,salary)、(area,age)、(area)三个索引，这被称为最佳左前缀特性。</p>
<p>因此我们在创建复合索引时应该将最常用作限制条件的列放在最左边，依次递减。</p>
<p>3，索引不会包含有NULL值的列</p>
<p>只要列中包含有NULL值都将不会被包含在索引中，复合索引中只要有一列含有NULL值，那么这一列对于此复合索引就是无效的。所以我们在数据库设计时不要让字段的默认值为NULL。</p>
<p>4，使用短索引</p>
<p>对串列进行索引，如果可能应该指定一个前缀长度。例如，如果有一个CHAR(255)的 列，如果在前10 个或20 个字符内，多数值是惟一的，那么就不要对整个列进行索引。短索引不仅可以提高查询速度而且可以节省磁盘空间和I/O操作。</p>
<p>5，排序的索引问题</p>
<p>mysql查询只使用一个索引，因此如果where子句中已经使用了索引的话，那么order by中的列是不会使用索引的。因此数据库默认排序可以符合要求的情况下不要使用排序操作；尽量不要包含多个列的排序，如果需要最好给这些列创建复合索引。</p>
<p>6，like语句操作</p>
<p>一般情况下不鼓励使用like操作，如果非使用不可，如何使用也是一个问题。like “%aaa%” 不会使用索引而like “aaa%”可以使用索引。</p>
<p>7，不要在列上进行运算</p>
<p>select* from users where</p>
<p>YEAR(adddate)</p>
<p>8，不使用NOT IN和操作</p>
<p>NOTIN和操作都不会使用索引将进行全表扫描。NOT IN可以NOT EXISTS代替，id3则可使用id&gt;3 or id</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/01/14/mysql/sql_数据库性能优化/" data-id="ckcc5iwq2009jq4uwbk77h0uz" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mysql/">mysql</a></li></ul>

    </footer>
  </div>
  
</article>


  
    <article id="post-mysql/sql_数据库进阶" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2019/01/14/mysql/sql_数据库进阶/" class="article-date">
  <time datetime="2019-01-14T02:42:06.000Z" itemprop="datePublished">2019-01-14</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a class="article-title" href="/2019/01/14/mysql/sql_数据库进阶/">数据库-进阶</a>
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="1-编码mysql"><a href="#1-编码mysql" class="headerlink" title="1  编码mysql"></a>1  编码mysql</h2><h4 id="1-1-查看mysql编码"><a href="#1-1-查看mysql编码" class="headerlink" title="1.1 查看mysql编码"></a>1.1 查看mysql编码</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">mysql&gt; show variables like &apos;character%&apos;;</span><br><span class="line">+--------------------------+----------------------------+</span><br><span class="line">| Variable_name            | Value                      |</span><br><span class="line">+--------------------------+----------------------------+</span><br><span class="line">| character_set_client     | utf8                       |</span><br><span class="line">| character_set_connection | utf8                       |</span><br><span class="line">| character_set_database   | latin1                     |</span><br><span class="line">| character_set_filesystem | binary                     |</span><br><span class="line">| character_set_results    | utf8                       |</span><br><span class="line">| character_set_server     | latin1                     |</span><br><span class="line">| character_set_system     | utf8                       |</span><br><span class="line">| character_sets_dir       | /usr/share/mysql/charsets/ |</span><br><span class="line">+--------------------------+----------------------------+</span><br></pre></td></tr></table></figure>
<h4 id="1-2-设置mysql编码"><a href="#1-2-设置mysql编码" class="headerlink" title="1.2 设置mysql编码"></a>1.2 设置mysql编码</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"># vi /etc/my.cnf</span><br><span class="line">如下(少补)：</span><br><span class="line"></span><br><span class="line">[mysqld]</span><br><span class="line">character-set-server=utf8 </span><br><span class="line">collation-server=utf8_general_ci </span><br><span class="line">sql_mode=&apos;NO_ENGINE_SUBSTITUTION&apos;</span><br><span class="line"></span><br><span class="line">[mysql]</span><br><span class="line">default-character-set = utf8</span><br><span class="line"></span><br><span class="line">[mysql.server]</span><br><span class="line">default-character-set = utf8</span><br><span class="line"></span><br><span class="line">[mysqld_safe]</span><br><span class="line">default-character-set = utf8</span><br><span class="line"></span><br><span class="line">[client]</span><br><span class="line">default-character-set = utf8</span><br><span class="line"></span><br><span class="line">重启mysql</span><br><span class="line"></span><br><span class="line"># service mysqld restart</span><br><span class="line">再次查看编码：</span><br><span class="line"></span><br><span class="line"># mysql -uroot -p</span><br><span class="line">mysql&gt; show variables like &apos;character%&apos;;</span><br><span class="line">+--------------------------+----------------------------+</span><br><span class="line">| Variable_name | Value |</span><br><span class="line">+--------------------------+----------------------------+</span><br><span class="line">| character_set_client | utf8 |</span><br><span class="line">| character_set_connection | utf8 |</span><br><span class="line">| character_set_database | utf8 |</span><br><span class="line">| character_set_filesystem | binary |</span><br><span class="line">| character_set_results | utf8 |</span><br><span class="line">| character_set_server | utf8 |</span><br><span class="line">| character_set_system | utf8 |</span><br><span class="line">| character_sets_dir | /usr/share/mysql/charsets/ |</span><br><span class="line">+--------------------------+----------------------------+</span><br><span class="line">8 rows in set (0.00 sec)</span><br></pre></td></tr></table></figure>
<h2 id="2-mysql的目录及配置文件"><a href="#2-mysql的目录及配置文件" class="headerlink" title="2  mysql的目录及配置文件"></a>2  mysql的目录及配置文件</h2><p>A<strong>/etc/my.cnf</strong> 这是mysql的主配置文件</p>
<p>B/var/lib/mysql   mysql数据库的数据库文件存放位置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql etc]# cd /var/lib/mysql/</span><br><span class="line">[root@mysql mysql]# ll</span><br><span class="line">total 176172</span><br><span class="line">-rw-rw----. 1 mysql mysql       56 Oct 20 00:10 auto.cnf</span><br><span class="line">-rw-rw----. 1 mysql mysql 79691776 Oct 21 04:46 ibdata1</span><br><span class="line">-rw-rw----. 1 mysql mysql 50331648 Oct 21 04:46 ib_logfile0</span><br><span class="line">-rw-rw----. 1 mysql mysql 50331648 Oct 20 00:09 ib_logfile1</span><br><span class="line">drwx------. 2 mysql mysql     4096 Oct 21 01:38 test11</span><br><span class="line">drwx------. 2 mysql mysql     4096 Oct 21 04:45 menagerie</span><br><span class="line">drwx--x--x. 2 mysql mysql     4096 Oct 20 00:09 mysql</span><br><span class="line">-rw-r-----. 1 mysql root      2219 Oct 20 00:14 mysql.err</span><br><span class="line">-rw-rw----. 1 mysql mysql        5 Oct 20 00:10 mysql.pid</span><br><span class="line">srwxrwxrwx. 1 mysql mysql        0 Oct 20 00:10 mysql.sock</span><br><span class="line">drwx------. 2 mysql mysql     4096 Oct 20 00:09 performance_schema</span><br><span class="line">-rw-r--r--. 1 root  root       111 Oct 20 00:09 RPM_UPGRADE_HISTORY</span><br><span class="line">-rw-r--r--. 1 mysql mysql      111 Oct 20 00:09 RPM_UPGRADE_MARKER-LAST</span><br><span class="line">drwxr-xr-x. 2 mysql mysql     4096 Oct 20 00:09 test</span><br></pre></td></tr></table></figure>
<p>我们的mysql数据库的数据库文件通常是存放在了/ver/lib/mysql这个目录下</p>
<p>C/var/log/mysql数据库的日志输出存放位置</p>
<p>D查看端口。Netstat –nltp 看是否能找到3306的端口</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">[root@mysql menagerie]# netstat -nltp</span><br><span class="line">Active Internet connections (only servers)</span><br><span class="line">Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   </span><br><span class="line">tcp        0      0 0.0.0.0:57958               0.0.0.0:*                   LISTEN      1306/rpc.statd      </span><br><span class="line">tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      1284/rpcbind        </span><br><span class="line">tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1573/sshd           </span><br><span class="line">tcp        0      0 127.0.0.1:631               0.0.0.0:*                   LISTEN      1362/cupsd          </span><br><span class="line">tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1654/master         </span><br><span class="line">tcp        0      0 :::3306                     :::*                        LISTEN      37860/mysqld        </span><br><span class="line">tcp        0      0 :::49647                    :::*                        LISTEN      1306/rpc.statd      </span><br><span class="line">tcp        0      0 :::111                      :::*                        LISTEN      1284/rpcbind        </span><br><span class="line">tcp        0      0 :::22                       :::*                        LISTEN      1573/sshd           </span><br><span class="line">tcp        0      0 ::1:631                     :::*                        LISTEN      1362/cupsd          </span><br><span class="line">tcp        0      0 ::1:25                      :::*                        LISTEN      1654/master</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">[root@mysql mysql]#  cat mysql.pid</span><br><span class="line">37860</span><br></pre></td></tr></table></figure>
<h2 id="3-数据库-原理部分"><a href="#3-数据库-原理部分" class="headerlink" title="3  数据库-原理部分"></a>3  数据库-原理部分</h2><p>常用的术语</p>
<h4 id="3-1数据模型"><a href="#3-1数据模型" class="headerlink" title="3.1数据模型"></a>3.1数据模型</h4><p>​    数据模型（Data model）是数据库结构的基础，是用来描述数据的一组概念和定义，数据模型主要有三个要素：数据结构数据操作数据约束条件。</p>
<p>数据结构：对象类型的集合，是对静态属性的描述。</p>
<p>数据操作：是对数据库中的各种对象性数据，允许执行的操作的集合，如增删改查等；数据操作是对系统动态热性的描述。</p>
<p>数据的约束条件：是一组完整性规则的集合，也就是说，对于具体的应用必须先遵循特定的语义约束条件。比如：性别只能取  “男”或者“女”中的之一。考试成绩：（满分100）只能是0-100的数值。</p>
<h4 id="3-2数据库"><a href="#3-2数据库" class="headerlink" title="3.2数据库"></a>3.2数据库</h4><p>​    数据库（database）是长期存储在计算机外存上有结构，可共享的数据集合；数据库中的数据按照一定的数据模型描述组织和存储，具有较小的冗余度，较高的数据独立性和可扩展性，并可以为多个用户共享。</p>
<p>常见数据库分类：</p>
<p>关系型数据库：如：MySQL，oracle，sqlserver</p>
<p>非关系型数据库：如：redis，hbase等</p>
<h4 id="3-3数据库管理系统"><a href="#3-3数据库管理系统" class="headerlink" title="3.3数据库管理系统"></a>3.3数据库管理系统</h4><p>​    数据库管理系统（database managerment system， DBMS）是指数据库系统中对数据库进行管理的软件系统，是数据库系统的核心组成部分。数据库的一切操作，如增删改查以及各种控制，都是通过DBMS进行的。</p>
<p>具有以下4个基本的功能：</p>
<p>1数据定义功能</p>
<p>用户可以通过DBMS提供的数据定义语言对数据库的数据进行定义。</p>
<p>2数据操纵功能</p>
<p>用户可以通过数据操纵语言实现对数据库的增删改查操作</p>
<p>3数据库运行管理</p>
<p>管理数据库的运行是DBMS运行时的核心工作。所有访问数据库的操作都要在DBMS的统一管理下进行，以保证数据的安全性完整性一致性以及多用户对数据库的并发使用。</p>
<p>4数据库的建立和维护</p>
<p>建立数据库，包括数据库初始数据的输入与数据转换等。维护数据库，包括数据库的转储与恢复，数据库的重组织，性能监控和分析。</p>
<h4 id="3-4数据库系统相关人员"><a href="#3-4数据库系统相关人员" class="headerlink" title="3.4数据库系统相关人员"></a>3.4数据库系统相关人员</h4><p>数据库系统的相关人员是数据库系统的重要组成部分，具体可以分为以下的三类人员</p>
<p>1数据库管理员</p>
<p>职责：负责数据库的建立使用维护的专门人员</p>
<p>2应用程序开发人员</p>
<p>职责：开发数据库应用程序的人员，可以使用数据库管理系统的所有功能。</p>
<p>3最终用户</p>
<p>职责：一般来说，是通过应用程序使用数据库的人员，最终用户无需自己编写应用程序。</p>
<h4 id="3-5数据库系统"><a href="#3-5数据库系统" class="headerlink" title="3.5数据库系统"></a>3.5数据库系统</h4><p>​    数据库系统（database system DBS）是由硬件系统，数据库管理系统，数据库，数据库应用程序，数据库系统相关人员构成的人-机系统，是指有数据库的整个计算机系统。</p>
<p>说明：在许多场合下，数据库，数据库管理系统，数据库系统不做严格区分；</p>
<h2 id="4-关系代数分类"><a href="#4-关系代数分类" class="headerlink" title="4 关系代数分类"></a>4 关系代数分类</h2><h4 id="4-1-基本运算"><a href="#4-1-基本运算" class="headerlink" title="4.1 基本运算"></a>4.1 基本运算</h4><p>​    并差笛卡尔积选择投影；</p>
<p>关系代数的基本操作（原始运算）：“选择”“投影”笛卡尔积（也叫做“叉积”或“交叉连接”）并集差集和“重命名”。</p>
<h4 id="4-2-组合运算"><a href="#4-2-组合运算" class="headerlink" title="4.2 组合运算"></a>4.2 组合运算</h4><p>​    交连接自然连接和除；</p>
<p>​    其中最重要的是<strong>交集除法和自然连接</strong>。(inner join     [join])</p>
<h4 id="4-3-扩充的关系代数操作"><a href="#4-3-扩充的关系代数操作" class="headerlink" title="4.3 扩充的关系代数操作"></a>4.3 扩充的关系代数操作</h4><p>​    外连接（左外和右外）外部并和半连接；(left join ,right join)</p>
<h2 id="5-数据库设计"><a href="#5-数据库设计" class="headerlink" title="5 数据库设计"></a>5 数据库设计</h2><p>关系型数据库的设计分为以下5个阶段：</p>
<h4 id="5-1需求分析"><a href="#5-1需求分析" class="headerlink" title="5.1需求分析"></a>5.1需求分析</h4><p>(1)      明确用户需求，到底做什么？</p>
<h4 id="5-2概念模式设计"><a href="#5-2概念模式设计" class="headerlink" title="5.2概念模式设计"></a>5.2概念模式设计</h4><p>(1)     该阶段是整个数据库设计的关键，它通过对用户需求进行综合归纳与抽象。主要是通过E-R图表示。</p>
<p>(2)      优点：</p>
<p>A简单明了，容易理解</p>
<p>B独立于计算机与具体的RDBMS无关。</p>
<p>(3)      E-R模型的基本元素</p>
<p>A实体（Entity） 如：学生</p>
<p>B属性（attribute）如：姓名</p>
<p>C键码（key）如：身份证号码；</p>
<p>D关系（relationship）如：两个实体之间的关系</p>
<p>a)        一对一（1:1）： 一个人一个身份证号码；一个学校一个校长</p>
<p>b)       一对多（1：n）：学校和老师的关系</p>
<p>c)        多对多（n：n）：学生选课，一个学生可以选择多门课程，一门课程课被多名学生进行选修。</p>
<p>EE-R符号表示：</p>
<h4 id="5-3-逻辑模式设计"><a href="#5-3-逻辑模式设计" class="headerlink" title="5.3 逻辑模式设计"></a>5.3 逻辑模式设计</h4><p>(1)      该阶段会涉及到更多的概念，方法，理论。</p>
<p>(2)      主要任务：</p>
<p>A与具体的数据库相关</p>
<p>B规范化处理，尽可能的消除关系操作过程中的异常情况。</p>
<p>CE-R图转换为如下的关系模式</p>
<p>电影（片名，出品年份，影片长度，影片类型，公司名称）</p>
<p>明星（姓名，联系地址，公司名称）</p>
<p>扮演（片名，出品年份，姓名，角色）</p>
<p>影片公司（公司名称，地址）</p>
<p>卡通片（片名，出品年份，设计平台）</p>
<h4 id="5-4-数据库实施"><a href="#5-4-数据库实施" class="headerlink" title="5.4 数据库实施"></a>5.4 数据库实施</h4><p>(1)      创建数据库，定义数据库结构，组织数据入库，调试数据库并进行数据库的试运行。</p>
<h4 id="5-5-数据库的运行和维护"><a href="#5-5-数据库的运行和维护" class="headerlink" title="5.5 数据库的运行和维护"></a>5.5 数据库的运行和维护</h4><p>(1)      数据库正式运行之后，对数据库运行过程中对其进行评价，调整，修改，调优等。</p>
<p>#6数据库设计遵循的原则</p>
<h3 id="6-1-范式概念"><a href="#6-1-范式概念" class="headerlink" title="6.1 范式概念"></a>6.1 范式概念</h3><p>概念：范式就是符合某一规范级别的关系模式的集合。共有7种范式：</p>
<p>1NF ⊃2NF⊃3NF⊃BCNF⊃4NF⊃5NF⊃6NF</p>
<h4 id="6-1-1-第一范式（First-Normal-Form）"><a href="#6-1-1-第一范式（First-Normal-Form）" class="headerlink" title="6.1.1 第一范式（First Normal Form）"></a>6.1.1 第一范式（First Normal Form）</h4><p>如果一个关系模式R的所有属性都是不可分割的基本数据项，则这个关系属于第一范式。</p>
<p>举例说明：(学生选课：学号，姓名，系别，系部地址，课程名称，课程成绩)</p>
<p>Student(s_no,s_name,s_dept,s_location,s_course_name,s_grade)</p>
<p>注：1NF是关系模式应具备的最起码的条件，如果数据库设计不能满足第一范式，就不能称作是关系模式；关系数据库设计研究的关系规范化是在1NF基础之上进行的。</p>
<h4 id="6-1-2-第二范式（Second-Normal-Form）"><a href="#6-1-2-第二范式（Second-Normal-Form）" class="headerlink" title="6.1.2 第二范式（Second Normal Form）"></a>6.1.2 第二范式（Second Normal Form）</h4><p>定义：若关系模式R属于第一范式，且每个非主属性都是完全函数依赖于主键，则R属于第二范式。</p>
<p>说明：从2NF的定义可以看出，从2NF开始讨论的是主键和非主属性之间的函数依赖关系，所以分析关系模式是属于2NF，首先指明关系模式的主键，然后在讨论非主属性和主键之间的函数依赖关系。</p>
<p>例如：选课关系模式</p>
<p>SC（s_no,c_no,score）中，主键为（s_no,c_no），而非主属性score与主键之间不存在部分函数依赖关系，所以关系模式SC属于2NF</p>
<h4 id="6-1-3-第三范式（Third-Normal-Form）"><a href="#6-1-3-第三范式（Third-Normal-Form）" class="headerlink" title="6.1.3 第三范式（Third Normal Form）"></a>6.1.3 第三范式（Third Normal Form）</h4><p>定义：若关系模式R属于第一范式，且每个非主属性都不传递函数依赖于主键，则R属于第三范式。</p>
<p>说明：3NF说明的是非主属性和主键之间的函数依赖关系</p>
<p>例如：选课关系模式</p>
<p>SC（s_no,c_no,score）中,由于除了主键之外，只有一个非主属性score，所以score不可能构成与主键之间的传递函数依赖，所以SC属于3NF</p>
<h4 id="6-1-4-BCNF（Boyce-Codd-Normal-Form）"><a href="#6-1-4-BCNF（Boyce-Codd-Normal-Form）" class="headerlink" title="6.1.4 BCNF（Boyce-Codd Normal Form）"></a>6.1.4 BCNF（Boyce-Codd Normal Form）</h4><p>定义：若关系模式R属于第一范式，且每个属性都不传递依赖于主键，则R属于BC范式。</p>
<p>说明：也就是说，在关系模式R中，凡是决定因素的属性或属性集包含键码，决定因素是函数依赖的左部属性集，比如X-&gt;Y，X称为决定因素。</p>
<p>由BC范式的定义可以得到以下的结论，一个满足BC范式的关系模式有：</p>
<p>​    1所有非主属性对每一个候选码都是完全函数依赖</p>
<p>​    2所有的主属性对每一个不包含它的候选码都是完全函数依赖</p>
<p>​    3没有任何属性完全函数依赖于非候选码的任何一组属性</p>
<h2 id="7-事务并发操作出现几种问题"><a href="#7-事务并发操作出现几种问题" class="headerlink" title="7 事务并发操作出现几种问题"></a>7 事务并发操作出现几种问题</h2><p>​    所谓事务，是用户定义的一个数据库操作序列，是数据库环境中的逻辑工作单元，是一个不可分割的整体。</p>
<p>事务的这个4个特性简称为ACID特性，事务ACID特性可能遭到破坏的因素有：</p>
<pre><code>①多个事务并发执行，不同事务的操作交叉执行；

②事务在运行过程中被强行终止。
</code></pre><p>如何保证在多个事务并发执行的过程中不发生上述的两种情况，是数据库管理系统并发控制的主要责任。</p>
<h4 id="7-1-丢失修改数据"><a href="#7-1-丢失修改数据" class="headerlink" title="7.1 丢失修改数据"></a>7.1 丢失修改数据</h4><pre><code>举例：银行卡有100元，事务A取10元，事务B取10元，事务AB两人同时取钱，初始值都是100
</code></pre><h4 id="7-2-读“脏”数据"><a href="#7-2-读“脏”数据" class="headerlink" title="7.2 读“脏”数据"></a>7.2 读“脏”数据</h4><pre><code>数据库技术中，如果正常提交的事务A使用了事务B未提交的撤销数据，这种数据成为“脏数据”，会造成数据的脏读和污读。
</code></pre><h4 id="7-3-不一致分析"><a href="#7-3-不一致分析" class="headerlink" title="7.3 不一致分析"></a>7.3 不一致分析</h4><pre><code>造成这种数据不一致的主要原因是并发执行的两个事务中，一个事务在读取数据时，另一个事务正在修改同一个数据。这样就可能导致两个事务的相互干扰及“读”事务的错误执行结果。
</code></pre><h2 id="8-数据库并发的控制（了解部分）"><a href="#8-数据库并发的控制（了解部分）" class="headerlink" title="8 数据库并发的控制（了解部分）"></a>8 数据库并发的控制（了解部分）</h2><h4 id="8-1-并发调度的可串行化"><a href="#8-1-并发调度的可串行化" class="headerlink" title="8.1 并发调度的可串行化"></a>8.1 并发调度的可串行化</h4><pre><code>可串行化准则：多个事务的并发执行时正确的，当且仅当其结果按某一次序串行执行它们时的结果相同，这种调度策略称为可串行化调度。可串行化是并发事务正确性的准则，一个给定的并发调度，当且仅当它是可串行化的，才认为是正确的。
</code></pre><h4 id="8-2-封锁"><a href="#8-2-封锁" class="headerlink" title="8.2 封锁"></a>8.2 封锁</h4><p>封锁是实现并发控制的非常重要的技术。封锁是指某事务在对某数据对象进行操作以前，先请求系统对其加锁，成功加锁之后该事务就对该数据对象有了控制权，只有该事务对其进行解锁之后，其他的事务才能更新它，DBMS有两种锁：</p>
<p>①  排它锁（也称作X锁）</p>
<p>​    如果事务T在对某个数据对象实施了X锁，那么其他的事务必须要等到T事务接触对该数据对象的X锁之后，才能对这个数据进行加锁。</p>
<p>②  共享锁（也称作S锁）</p>
<p>​     如果事务T在对某个数据对象实施了S锁，那么其他的事务也能对该数据对象实施S锁，但是对这个数据对象施加的所有S锁都接触之前不允许任何事务对该数据对象实施X锁。</p>
<h4 id="8-3-死锁"><a href="#8-3-死锁" class="headerlink" title="8.3 死锁"></a>8.3 死锁</h4><pre><code>封锁技术可以避免一些并发操作引起的不一致错误，但也会产生其他的一些问题，活锁和死锁。
</code></pre><p>①  活锁</p>
<p>如果某个事务处在永远等待的状态，得不到封锁的机会，这种现象为活锁，避免这种锁最好的方法就是采用先来先服务的策略。</p>
<p>②  死锁</p>
<p>两个或两个以上的事务都处于等待状态每个事务都在等待对方事务接触封锁，它才能继续执行下去，这样任何事务都处于等待状态而无法继续执行的现象称为死锁</p>
<p>解决死锁问题方法有两类：</p>
<p>A 死锁的预防</p>
<p>B 死锁的诊断与预防</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2019/01/14/mysql/sql_数据库进阶/" data-id="ckcc5iwp10083q4uwjcp6qq96" class="article-share-link">Teilen</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mysql/">mysql</a></li></ul>

    </footer>
  </div>
  
</article>


  


  <nav id="page-nav">
    
    <a class="extend prev" rel="prev" href="/page/2/">&laquo; zurück</a><a class="page-number" href="/">1</a><a class="page-number" href="/page/2/">2</a><span class="page-number current">3</span><a class="page-number" href="/page/4/">4</a><a class="page-number" href="/page/5/">5</a><span class="space">&hellip;</span><a class="page-number" href="/page/15/">15</a><a class="extend next" rel="next" href="/page/4/">weiter &raquo;</a>
  </nav>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Design-Patterns/">Design Patterns</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Git/">Git</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Html/">Html</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Http/">Http</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/">JavaScript</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Sort/">Sort</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/algorithm/">algorithm</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/ali-weixin-pay/">ali/weixin pay</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/docker/">docker</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/elasticsearch/">elasticsearch</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/go/">go</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/idea/">idea</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/">java</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/jvm/">jvm</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/linux/">linux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/logstash/">logstash</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mysql/">mysql</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/php/">php</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/pytest/">pytest</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/">python</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/util/">util</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/vue/">vue</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/wechat/">wechat</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/我的世界/">我的世界</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/消息队列/">消息队列</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/线程/">线程</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Design-Patterns/" style="font-size: 16.36px;">Design Patterns</a> <a href="/tags/Git/" style="font-size: 10px;">Git</a> <a href="/tags/Html/" style="font-size: 10px;">Html</a> <a href="/tags/Http/" style="font-size: 12.73px;">Http</a> <a href="/tags/JavaScript/" style="font-size: 15.45px;">JavaScript</a> <a href="/tags/Sort/" style="font-size: 18.18px;">Sort</a> <a href="/tags/algorithm/" style="font-size: 11.82px;">algorithm</a> <a href="/tags/ali-weixin-pay/" style="font-size: 13.64px;">ali/weixin pay</a> <a href="/tags/docker/" style="font-size: 17.27px;">docker</a> <a href="/tags/elasticsearch/" style="font-size: 10px;">elasticsearch</a> <a href="/tags/go/" style="font-size: 11.82px;">go</a> <a href="/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/tags/idea/" style="font-size: 10px;">idea</a> <a href="/tags/java/" style="font-size: 20px;">java</a> <a href="/tags/jvm/" style="font-size: 11.82px;">jvm</a> <a href="/tags/linux/" style="font-size: 18.18px;">linux</a> <a href="/tags/logstash/" style="font-size: 12.73px;">logstash</a> <a href="/tags/mysql/" style="font-size: 14.55px;">mysql</a> <a href="/tags/php/" style="font-size: 11.82px;">php</a> <a href="/tags/pytest/" style="font-size: 10px;">pytest</a> <a href="/tags/python/" style="font-size: 13.64px;">python</a> <a href="/tags/springboot/" style="font-size: 17.27px;">springboot</a> <a href="/tags/util/" style="font-size: 19.09px;">util</a> <a href="/tags/vue/" style="font-size: 10px;">vue</a> <a href="/tags/wechat/" style="font-size: 10.91px;">wechat</a> <a href="/tags/我的世界/" style="font-size: 10px;">我的世界</a> <a href="/tags/消息队列/" style="font-size: 10.91px;">消息队列</a> <a href="/tags/线程/" style="font-size: 11.82px;">线程</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archiv</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/05/">May 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/04/">April 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/03/">March 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/01/">January 2020</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/10/">October 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/08/">August 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/06/">June 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/04/">April 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">March 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/02/">February 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/01/">January 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/12/">December 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">October 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/09/">September 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/07/">July 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/06/">June 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/05/">May 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">April 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">March 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/02/">February 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">January 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">December 2017</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">letzter Beitrag</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2020/05/17/linux/linux_shell/">linux—shell</a>
          </li>
        
          <li>
            <a href="/2020/05/16/linux/linux_awk_sed/">linux-awk\sed 示例</a>
          </li>
        
          <li>
            <a href="/2020/04/11/linux/linux_bash/">linux—bash</a>
          </li>
        
          <li>
            <a href="/2020/03/29/hello-world/">Hello World</a>
          </li>
        
          <li>
            <a href="/2020/03/16/go基础/">go基础知识</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2020 vchen<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



  </div>
</body>
</html>